how can i make a uitableview container to bounce within the view - objective-c

ok, so this is pretty simple one, but i hope i could explain this clearly - i have a table view that i would like to inset into a container, and then have the table bounces when it reaches the top / bottom. So far, I was able to put my table in a container, but the container is fixed on the view, while the table inside the container bounces. Again, I am looking for a way to fix the table to the container, while having the container bouncing.
Here is what I was able to do, following the code:
What I want to accomplish is to have the black box bouncing rather than the table within it.
my ViewDidLoad in the view controller .m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//General View Setup
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"backgroundimage.png"]];
self.view.backgroundColor = background;
//Table View Data
listOfItems = [[NSMutableArray alloc] init];
NSArray *appleComputers = [NSArray arrayWithObjects:#"iPhone",#"iPod",#"MacBook",#"MacBook Pro",nil];
NSDictionary *appleComputersDict = [NSDictionary dictionaryWithObject:appleComputers forKey:#"Computers"];
NSArray *otherComputers = [NSArray arrayWithObjects:#"HP", #"Dell", #"Windows", #"Sony", #"Ivory", #"IBM", nil];
NSDictionary *otherComputersDict = [NSDictionary dictionaryWithObject:otherComputers forKey:#"Computers"];
[listOfItems addObject:appleComputersDict];
[listOfItems addObject:otherComputersDict];
self.navigationItem.title = #"Computers";
// Create a table
tblSimpleTable.delegate = self;
CGRect cgRct = CGRectMake(10, 50, 300, 300);
tblSimpleTable = [[UITableView alloc] initWithFrame:cgRct style:UITableViewStyleGrouped]; // Initilize the table
[tblSimpleTable setBackgroundColor:[UIColor blackColor]];
tblSimpleTable.sectionHeaderHeight = 30.0;
tblSimpleTable.sectionFooterHeight = 30.0;
tblSimpleTable.delegate = self;
tblSimpleTable.dataSource = self;
[self.view addSubview:tblSimpleTable];
//Create the header
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 40)];
headerLabel.text = NSLocalizedString(#"Header for the table", #"");
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor yellowColor];
headerLabel.shadowOffset = CGSizeMake(0, 1);
headerLabel.font = [UIFont boldSystemFontOfSize:22];
headerLabel.backgroundColor = [UIColor clearColor];
[containerView addSubview:headerLabel];
self.tblSimpleTable.tableHeaderView = containerView;
}

why don’t you use UIScrollView for that.
I had tested your code & done required changes. Hope you like it.
Code :
(this is your .h file)
#import <UIKit/UIKit.h>
#interface tableScrollViewController : UIViewController
<UITableViewDelegate,UITableViewDataSource, UIScrollViewDelegate> {
UITableView *tblSimpleTable;
NSMutableArray *listOfItems;
NSMutableArray *appleComputers,*otherComputers;
UIScrollView *scrollView;
}
#end
(this is your .m file)
- (void)viewDidLoad {
[super viewDidLoad];
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 600)];
scrollView.delegate = self;
scrollView.backgroundColor = [UIColor grayColor];
scrollView.contentSize = CGSizeMake(300, 800);
appleComputers = [[NSMutableArray alloc] init]; // I made it by my style
[appleComputers addObject: #"iPhone"];
[appleComputers addObject:#"iPod"];
[appleComputers addObject:#"MacBook"];
[appleComputers addObject:#"MacBook Pro"];
otherComputers = [[NSMutableArray alloc] init];
[otherComputers addObject: #"HP"];
[otherComputers addObject:#"Dell"];
[otherComputers addObject:#"Windows"];
[otherComputers addObject:#"Sony"];
[otherComputers addObject:#"Ivory"];
[otherComputers addObject:#"IBM"];
self.navigationItem.title = #"Computers";
// Create a table
tblSimpleTable.delegate = self;
CGRect cgRct = CGRectMake(10, 50, 300, 600);
tblSimpleTable = [[UITableView alloc] initWithFrame:cgRct
style:UITableViewStyleGrouped]; // Initilize the table
[tblSimpleTable setBackgroundColor:[UIColor blackColor]];
tblSimpleTable.sectionHeaderHeight = 30.0;
tblSimpleTable.sectionFooterHeight = 30.0;
tblSimpleTable.scrollEnabled = NO;
tblSimpleTable.delegate = self;
tblSimpleTable.dataSource = self;
[scrollView addSubview:tblSimpleTable];
self.view = scrollView;
//Create the header
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 40)];
headerLabel.text = NSLocalizedString(#"Header for the table", #"");
headerLabel.textColor = [UIColor whiteColor];
headerLabel.shadowColor = [UIColor yellowColor];
headerLabel.shadowOffset = CGSizeMake(0, 1);
headerLabel.font = [UIFont boldSystemFontOfSize:22];
headerLabel.backgroundColor = [UIColor clearColor];
[containerView addSubview:headerLabel];
tblSimpleTable.tableHeaderView = containerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(section == 0)
return [appleComputers count];
else if(section == 1)
return [otherComputers count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier] autorelease];
}
if(indexPath.section == 0)
cell.text = [NSString stringWithFormat:#"%#“,
[appleComputers objectAtIndex:indexPath.row]];
else if(indexPath.section == 1)
cell.text = [NSString stringWithFormat:#"%#“,
[otherComputers objectAtIndex:indexPath.row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath
{
// do whatever here
}

Related

How to set delegate to UICollectionView in NSObject controller

How to add CollectionView in NSObject controller?
I have one NSObject controller which i am accessing on each ViewController. I already added some component on it like image view. Now I want to add CollectionView on it. I have written code as follows:
in AboutMe.h file
#interface AboutMe : NSObject<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
-(UIButton *) showAboutMeView:(UIViewController *)id;
#end
and in AboutMe.m file
#import "AboutMe.h"
#implementation AboutMe {
UIView *objMessageView;
UICollectionView *_collectionView
NSMutableArray *arrstrProfileImage;
NSMutableArray *arrstrUsersNameEn;
NSMutableArray *arrstrUsersNameMr;
}
-(UIButton *) showAboutMeView:(UIViewController *)id {
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenX = screenRect.origin.x;
CGFloat screenY = screenRect.origin.y;
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
arrstrProfileImage = [[NSMutableArray alloc] initWithObjects:#"male.png",#"female.png",nil];
arrstrUsersNameEn = [[NSMutableArray alloc] initWithObjects:#"Mr. (Corporator)",#"Mrs.(Corporator)", nil];
objMessageView = [[UIView alloc] initWithFrame:CGRectMake(screenX, screenY, screenWidth,screenHeight-64)];
objMessageView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.8f];
[id.view addSubview:objMessageView];
UIImageView *objUIImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, screenWidth, 150)];
objUIImageView.image = [UIImage imageNamed:#"abc.png"];
objUIImageView.contentMode = UIViewContentModeScaleAspectFit;
[objMessageView addSubview:objUIImageView];
UIButton *objUIButtonOk = [[UIButton alloc] initWithFrame:CGRectMake(screenX, screenHeight-120, screenWidth, 50)];
[objUIButtonOk setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
objUIButtonOk.titleLabel.font = [UIFont boldSystemFontOfSize:25];
[objUIButtonOk setTitle:#"OK" forState:UIControlStateNormal];
[objMessageView addSubview:objUIButtonOk];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
_collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(objMessageView.frame.origin.x+10, objUIImageView.frame.origin.y+objUIImageView.frame.size.height+5, objMessageView.frame.size.width-20, objUIButtonOk.frame.origin.y-(objUIImageView.frame.origin.y+objUIImageView.frame.size.height+25)) collectionViewLayout:layout];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
_collectionView.showsVerticalScrollIndicator = NO;
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor gray]];
[objMessageView addSubview:_collectionView];
return objUIButtonOk;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return arrstrProfileImage.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
UIImageView *objUIImageView;
UILabel *objUILabel;
for (UILabel *lbl in cell.contentView.subviews)
{
if ([lbl isKindOfClass:[UILabel class]])
{
[lbl removeFromSuperview];
}
}
for (UIImageView *img in cell.contentView.subviews)
{
if ([img isKindOfClass:[UIImageView class]])
{
[img removeFromSuperview];
}
}
cell.backgroundColor=[UIColor lightGrayColor];
cell.layer.cornerRadius = 3;
cell.layer.masksToBounds = YES;
objUIImageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width/2-50, cell.contentView.frame.origin.y+25, 100, 100)];
objUIImageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#",[arrstrProfileImage objectAtIndex:indexPath.row]]];
objUIImageView.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:objUIImageView];
objUILabel = [[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.frame.origin.x+5, objUIImageView.frame.size.height+20, cell.contentView.frame.size.width-10, cell.contentView.frame.size.height - (objUIImageView.frame.size.height+20))];
objUILabel.backgroundColor = [UIColor clearColor];
objUILabel.textAlignment = NSTextAlignmentCenter;
objUILabel.numberOfLines = 0;
objUILabel.lineBreakMode = NSLineBreakByWordWrapping;
objUILabel.font = [UIFont boldSystemFontOfSize:16];
objUILabel.textColor = [UIColor blackColor];
if ([[NSString stringWithFormat:#"%#",[UserDefault objectForKey:#"lang"]] isEqualToString:#"M"]) {
objUILabel.text = [arrstrUsersNameMr objectAtIndex:indexPath.row];
}else{
objUILabel.text = [arrstrUsersNameEn objectAtIndex:indexPath.row];
}
[cell.contentView addSubview:objUILabel];
return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(objMessageView.frame.size.width/2 -15,objMessageView.frame.size.width/2 -15);
}
#end
I am accessing this in ViewController as:
AboutMe *objAboutMe = [[AboutMe alloc] init];
UIButton *objBtn = [objAboutMe showAboutMeView:self];
[objBtn addTarget:self action:#selector(click:) forControlEvents:UIControlEventTouchUpInside];
A blank white view get loaded.
Here Problem is I am not able to set Delegate to CollectionView.
Please Help me in this.
You're CollectionView delegate won't work unless you change inheritation of your AboutMe class.
So you need to update this line and inherit from UIViewController:
#interface AboutMe : UICollectionViewController <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
Also I would make an additional suggestion. When working with method like this:
-(UIButton *) showAboutMeView:(UIViewController *)id {
Try to mantain only that code, that is related to creation and returning UIButton, so for example instantiation and operations with objMessageView could be placed in another method, etc.

How to set UIImageView image added in viewForHeaderInSection and set in another Method

How to set UIImageView image added in viewForHeaderInSection and set in another Method.
- (NSInteger)numberOfSectionsInTableView:(TQMultistageTableView *)mTableView
{
return 4;
}
- (UIView *)mTableView:(TQMultistageTableView *)mTableView viewForHeaderInSection:(NSInteger)section;
{
UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 90)];
header.layer.backgroundColor = [UIColor whiteColor].CGColor;
header.layer.masksToBounds = YES;
UILabel *sectionTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width - 110, 70)];
sectionTitleLabel.text = [sectionTitleArray objectAtIndex:section];
sectionTitleLabel.textAlignment = NSTextAlignmentCenter;
sectionTitleLabel.font = [UIFont fontWithName:#"Helvetica-Neue" size:15];
sectionTitleLabel.numberOfLines = 0;
sectionTitleLabel.contentMode = NSLineBreakByWordWrapping;
[header addSubview:sectionTitleLabel];
UIImageView *locationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 90, 0, 90, 90)];
locationImageView.image = [locationImageArray objectAtIndex:section];
locationImageView.backgroundColor = [UIColor brownColor];
[header addSubview:locationImageView];
UILabel *sectionLineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, header.frame.size.height - 1, self.view.frame.size.width, 1)];
sectionLineLabel.backgroundColor = [UIColor blackColor];
[header addSubview:sectionLineLabel];
discloserImageView = [[UIImageView alloc] initWithFrame:CGRectMake(locationImageView.frame.size.width - 50, 0, 40, 40)];
discloserImageView.image = [UIImage imageNamed:#"down-arrow.png"];
discloserImageView.backgroundColor = [UIColor brownColor];
discloserImageView.tag = section;
[locationImageView addSubview:discloserImageView];
return header;
}
- (void)mTableView:(TQMultistageTableView *)mTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"didSelectRow ----%ld",(long)indexPath.row);
}
#pragma mark - Header Open Or Close
- (void)mTableView:(TQMultistageTableView *)mTableView willOpenHeaderAtSection:(NSInteger)section
{
NSLog(#"Open Header ----%d",section);
// UITableViewHeaderFooterView *header = [self mTableView:mTableView viewForHeaderInSection:section];
UIView *headerView = [self mTableView:mTableView viewForHeaderInSection:section];
[[[headerView subviews] objectAtIndex:1] subviews];
NSLog(#"HeaderView :%#",headerView);
for (UIImageView *imageView in [[[headerView subviews] objectAtIndex:1] subviews]) {
if ([ imageView isKindOfClass:[UIImageView class]])
{
imageView.image = [UIImage imageNamed:#"up-arrow.png"];
}
}
}
In your code your header is not a UIImageView so your condition if ([header isKindOfClass:[UIImageView class]]) will never be true. Indeed, you add your UIImageView as a subview of a UIView.
What you can do instead is :
if ([[header subviews][0] isKindOfClass:[UIImageView class]])
{
UIImageView *imageViewChange =(UIImageView *) imageView;
imageViewChange.image = [UIImage imageName#"downArrow.png"];
}
Edit :
According to your edit, I think your best bet is to make your UIImageView a property as follows :
#interface YourViewController () {
UIImageView *imageViewChange;
}
and use it like that :
imageViewChange.image = [UIImage imageName#"downArrow.png"];

UicollectionView didSelectItemAtIndexPath is not called in uiTableviewcell

I am working on chat view. For this I have used this code :Chat Code
This is working fine. Now I have used UIcollectionView in UItableViewCell. Collection view is working fine. But the issue is didselect method is not called of UICollectionView as well as UITableView. Please help me. I need your help very badly.
I have used this code in UITableViewCell Class:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.backgroundColor = [UIColor clearColor];
if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0f) {
self.textLabel.backgroundColor = [UIColor whiteColor];
}
self.textLabel.font = [UIFont systemFontOfSize:14.0f];
self.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.textLabel.numberOfLines = 0;
self.textLabel.textAlignment = NSTextAlignmentLeft;
self.textLabel.textColor = [UIColor blackColor];
_timestampLabel = [[UILabel alloc] init];
_timestampLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
_timestampLabel.textAlignment = NSTextAlignmentCenter;
_timestampLabel.backgroundColor = [UIColor clearColor];
_timestampLabel.font = [UIFont systemFontOfSize:12.0f];
_timestampLabel.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1.0];
_timestampLabel.frame = CGRectMake(0.0f, 12, self.bounds.size.width, 18);
[self.contentView addSubview:_timestampLabel];
messageBackgroundView = [[UIImageView alloc] initWithFrame:self.textLabel.frame];
[self.contentView insertSubview:messageBackgroundView belowSubview:self.textLabel];
self.AvatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5,10+TOP_MARGIN, 50, 50)];
[self.contentView addSubview:self.AvatarImageView];
CALayer * l = [self.AvatarImageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:self.AvatarImageView.frame.size.width/2.0];
self.selectionStyle = UITableViewCellSelectionStyleNone;
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
[self.collectionView registerNib:[UINib nibWithNibName:#"ImageCollection" bundle:nil] forCellWithReuseIdentifier:#"Cell"];
[self.collectionView setUserInteractionEnabled:YES];
self.collectionView.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:self.collectionView];
[messageBackgroundView setUserInteractionEnabled:YES];
[self.contentView setUserInteractionEnabled:YES];
// UITapGestureRecognizer *lpgr // = [[UITapGestureRecognizer alloc] // initWithTarget:self action:#selector(tapRecognized:)]; // lpgr.numberOfTapsRequired
= 1; // lpgr.delegate = self; // [self.collectionView addGestureRecognizer:lpgr];
}
[self setUserInteractionEnabled:YES];
return self; }
In UIViewController I have used this code in tableView cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *L_CellIdentifier = #"SPHTextBubbleCell";
self.documentsArray = [[NSMutableArray alloc]init];
self.documentsArray = [[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"Attachments"];
SPHTextBubbleCell *cell = [tableView dequeueReusableCellWithIdentifier:L_CellIdentifier];
cell.userInteractionEnabled = YES;
if (cell == nil)
{
cell = [[SPHTextBubbleCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:L_CellIdentifier];
}
// cell.bubbletype=(([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1))?#"LEFT":#"RIGHT";
if ([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1) {
cell.bubbletype = #"RIGHT";
}
else
{
cell.bubbletype = #"LEFT";
}
[cell setBackgroundColor:[UIColor clearColor]];
cell.textLabel.text = [[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"Content"];
cell.textLabel.tag=indexPath.row;
NSString *dateString = [NSString stringWithFormat:#"%#",[self mfDateFromDotNetJSON:[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"UpdatedOn"]]];
NSLog(#"dateString..%#",dateString);
NSString *myString = [NSString stringWithFormat:#"%#",dateString];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss ZZZ";
NSDate *yourDate = [dateFormatter dateFromString:myString];
// NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
// [dateFormatter setTimeZone:utc];
dateFormatter.dateFormat = #"dd-MMM-yy HH:mm";
NSString *newString = [dateFormatter stringFromDate:yourDate];
NSLog(#"newString..%#",newString);
if ([self.documentsArray count]!=0)
{
cell.CustomDelegate = self;
[cell.collectionView setUserInteractionEnabled:YES];
[cell.collectionView setDelegate:self];
[cell.collectionView setDataSource:self];
cell.collectionView.delegate =self;
cell.collectionView.dataSource = self;
[cell.collectionView reloadData];
[cell.collectionView setHidden:NO];
[cell.collectionView setBackgroundColor:[UIColor clearColor]];
}
else
{
[cell.collectionView setHidden:YES];
}
cell.collectionView.tag =indexPath.row;
cell.timestampLabel.text = newString;
[cell.AvatarImageView sd_setImageWithURL:([[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"MessageFromId"]intValue] == 1)?[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",imageURLLive,[[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"SellerPicture"] valueForKey:#"PictureUrl"]]]:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",imageURLLive,[[[self.messagesArray objectAtIndex:indexPath.row]valueForKey:#"BuyerPicture"] valueForKey:#"PictureUrl"]]]
placeholderImage:[UIImage imageNamed:#"Nav-profile1.png"]];
return cell;
}
Thanks in advance.
If your problem is that your UICollectionView taps do not cause the UITableViewCell it is in to be selected then you can bypass this by subclassing UICollectionView and modifying the hitTest function to your liking.
See my answer here.
This one lets you tap on anything outside of collection view items to select the table cell, but collection view items themselves will block the taps and process them as needed.
Modifying the hitTest method wasn't working in my case. I decided to use UITapGestureRecognizer.
// Custom UITableViewCell
override func awakeFromNib() {
super.awakeFromNib()
let tapGR = UITapGestureRecognizer(target: self, action: #selector(collectionViewTapped(_:)))
tapGR.numberOfTapsRequired = 1
self.collectionView.addGestureRecognizer(tapGR)
}
func collectionViewTapped(gr: UITapGestureRecognizer) {
let point = gr.locationInView(self.collectionView)
if let indexPath = self.collectionView.indexPathForItemAtPoint(point) {
// Do stuff
}
}
Don't forget to set delegate and dataSource.
self.tableView.delegate = self;
self.tableView.dataSource = self;

UITableViewCell with alternate background color in customized cells

I'd like the background to of my UITableViewCells to have a different color every two cells displayed, but when I scroll down and back, they all get the same color. How can I get this effect knowing that my cells have different contentView size (according to their content) ?
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 20.0f
#define NAME_CELL_HEIGHT 20.0f
#import "CartCell.h"
#implementation CartCell
#synthesize nameLabel = _nameLabel;
#synthesize ingredientsLabel = _ingredientsLabel;
#synthesize myStore;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
myStore = [Store sharedStore];
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.nameLabel = nil;
self.ingredientsLabel = nil;
// SET "NAME" CELL
self.nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[self.nameLabel setLineBreakMode:UILineBreakModeWordWrap];
[self.nameLabel setMinimumFontSize:FONT_SIZE];
[self.nameLabel setNumberOfLines:1];
[self.nameLabel setTag:1];
self.nameLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18];
[self.nameLabel sizeToFit];
self.nameLabel.backgroundColor = [UIColor clearColor];
[[self contentView] addSubview:self.nameLabel];
// SET "INGREDIENTS" CELL
self.ingredientsLabel = [[UILabel alloc] initWithFrame:CGRectZero];
[self.ingredientsLabel setLineBreakMode:UILineBreakModeWordWrap];
[self.ingredientsLabel setMinimumFontSize:FONT_SIZE];
[self.ingredientsLabel setNumberOfLines:0];
[self.ingredientsLabel setFont:[UIFont systemFontOfSize:FONT_SIZE]];
[self.ingredientsLabel setTag:2];
self.ingredientsLabel.backgroundColor = [UIColor clearColor];
[[self contentView] addSubview:self.ingredientsLabel];
if (myStore.cellBackgroundShouldBeLight == YES) {
NSLog(#"clear [in] ? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
self.contentView.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = NO;
} else {
NSLog(#"clear [in] ? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
self.contentView.backgroundColor = [[UIColor alloc]initWithRed:187.0/255.0 green:268.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = YES;
}
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
UPDATE:
I'm know trying to set it in cellForRowAtIndexPath as it was suggested, but I get the same result: scrolling down worked fine the first time, but then scrolling up again messed up the cells background color.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CartCell";
CartCell *cell = (CartCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Recipes *info = [_fetchedResultsController objectAtIndexPath:indexPath];
if (cell == nil)
{
cell = [[CartCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// if (!cell.nameLabel) {
// cell.nameLabel = (UILabel*)[cell viewWithTag:1];
// // cell.nameLabel = (UILabel*)[cell viewWithTag:1];
// }
// if (!cell.ingredientsLabel)
// cell.ingredientsLabel = (UILabel*)[cell viewWithTag:2];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [info.ingredients sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[cell.nameLabel setFrame:CGRectMake(10, 10, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), NAME_CELL_HEIGHT)];
[cell.ingredientsLabel setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN + NAME_CELL_HEIGHT, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
// SETTING TEXT CONTENT
cell.nameLabel.text = info.name;
cell.ingredientsLabel.text = info.ingredients;
// SETTING BACKGROUND COLOR
// UIView *lab = [[UIView alloc] initWithFrame:cell.frame];
// [lab setBackgroundColor:[UIColor blueColor]];
if (myStore.cellBackgroundShouldBeLight == YES) {
NSLog(#"clear? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:84.0/255.0 blue:229.0/255.0 alpha:1];
// cell.backgroundView = lab;
// ingredientsLabel.backgroundColor = [UIColor clearColor];
// nameLabel.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1];
// [cell setBackgroundColor: [[UIColor alloc]initWithRed:87.0/255.0 green:168.0/255.0 blue:229.0/255.0 alpha:1]];
// [cell setBackgroundColor:[UIColor colorWithRed:.8 green:.8 blue:1 alpha:1]];
myStore.cellBackgroundShouldBeLight = NO;
} else {
// cell.contentView.tag = 2;
NSLog(#"clear? %#", myStore.cellBackgroundShouldBeLight ? #"Yes" : #"No");
cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:187.0/255.0 green:184.0/255.0 blue:229.0/255.0 alpha:1];
myStore.cellBackgroundShouldBeLight = YES;
}
return cell;
}
It is very simple, the indexPath tells you everything you need to know. If the indexPath.row is even then use one color. If the indexPath.row is odd use a different color.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
…
// SETTING BACKGROUND COLOR
// UIView *lab = [[UIView alloc] initWithFrame:cell.frame];
// [lab setBackgroundColor:[UIColor blueColor]];
if (indexPath.row % 2) {
cell.contentView.backgroundColor = [[[UIColor alloc]initWithRed:87.0/255.0 green:84.0/255.0 blue:229.0/255.0 alpha:1] autorelease];
} else {
cell.contentView.backgroundColor = [[[UIColor alloc]initWithRed:187.0/255.0 green:184.0/255.0 blue:229.0/255.0 alpha:1] autorelease];
}
…
return cell;
}
Your method is having problems because blindly assuming cells will be asked for in alternating pairs is a bad assumption. The tableView could ask for cells in any order is chooses. In your example, I believe cells could be asked for as follows. First, 0, 1,…, 9 are asked for. Next, you scroll down and 10, 11, and 12 are fetched. At this point, 0, 1, and 2 have gone off the screen. You scroll back up and 2 is asked for, but oh no, your model is on an odd number alternation, so you get the wrong color.
Use the -willDisplayCell method.
- (void)tableView: (UITableView *)tableView willDisplayCell: (UITableViewCell *)cell forRowAtIndexPath: (NSIndexPath *)indexPath {
if (indexPath.row %2) { //change the "%2" depending on how many cells you want alternating.
UIColor *altCellColor = [UIColor colorWithRed:255/255.0 green:237/255.0 blue:227/255.0 alpha:1.0]; //this can be changed, at the moment it sets the background color to red.
cell.backgroundColor = altCellColor;
}
else if (indexPath.row %2) {
UIColor *altCellColor2 = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.0]; //this can be changed, at the moment it sets the background color to white.
cell.backgroundColor = altCellColor2;
}
}
The appropriate place to change your cell's background color would be the "cellForRowAtIndexPath:" method, where the cells data gets filled out and returned to the table view.
One way to do this would be: When the data goes into the cell, change the background color depending on what row you're on.
Put the color on the cellForRowAtIndexPath: don't set on custom cell.
Take a look what I use to customize my table
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#if USE_CUSTOM_DRAWING
const NSInteger TOP_LABEL_TAG = 1001;
const NSInteger BOTTOM_LABEL_TAG = 1002;
UILabel *topLabel;
UILabel *bottomLabel;
#endif
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//
// Create the cell.
//
cell =
[[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
autorelease];
#if USE_CUSTOM_DRAWING
UIImage *indicatorImage = [UIImage imageNamed:#"indicator.png"];
cell.accessoryView =
[[[UIImageView alloc]
initWithImage:indicatorImage]
autorelease];
const CGFloat LABEL_HEIGHT = 20;
UIImage *image = [UIImage imageNamed:#"imageA.png"];
//
// Create the label for the top row of text
//
topLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT),
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:topLabel];
//
// Configure the properties for the text that are the same on every row
//
topLabel.tag = TOP_LABEL_TAG;
topLabel.backgroundColor = [UIColor clearColor];
topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
//
// Create the label for the top row of text
//
bottomLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT) + LABEL_HEIGHT,
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:bottomLabel];
//
// Configure the properties for the text that are the same on every row
//
bottomLabel.tag = BOTTOM_LABEL_TAG;
bottomLabel.backgroundColor = [UIColor clearColor];
bottomLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
bottomLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
bottomLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 2];
//
// Create a background image view.
//
cell.backgroundView =
[[[UIImageView alloc] init] autorelease];
cell.selectedBackgroundView =
[[[UIImageView alloc] init] autorelease];
#endif
}
#if USE_CUSTOM_DRAWING
else
{
for (UIView *sub in [cell.contentView subviews]) {
// if([sub class] == [UITableViewCellContentView class])
NSLog(#"this is uilabel %#",[sub class]);
}
topLabel = (UILabel *)[cell viewWithTag:TOP_LABEL_TAG];
bottomLabel = (UILabel *)[cell viewWithTag:BOTTOM_LABEL_TAG];
}
topLabel.text = [NSString stringWithFormat:#"Cell at row %ld.", [indexPath row]];
bottomLabel.text = [NSString stringWithFormat:#"Some other information.", [indexPath row]];
//
// Set the background and selected background images for the text.
// Since we will round the corners at the top and bottom of sections, we
// need to conditionally choose the images based on the row index and the
// number of rows in the section.
//
UIImage *rowBackground;
UIImage *selectionBackground;
NSInteger sectionRows = [aTableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"topAndBottomRow.png"];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected.png"];
}
else if (row == 0)
{
rowBackground = [UIImage imageNamed:#"topRow.png"];
selectionBackground = [UIImage imageNamed:#"topRowSelected.png"];
}
else if (row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"bottomRow.png"];
selectionBackground = [UIImage imageNamed:#"bottomRowSelected.png"];
}
else
{
rowBackground = [UIImage imageNamed:#"middleRow.png"];
selectionBackground = [UIImage imageNamed:#"middleRowSelected.png"];
}
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
// cell.backgroundView.backgroundColor = [UIColor colorWithPatternImage:rowBackground];
// cell.selectedBackgroundView.backgroundColor = [UIColor colorWithPatternImage:selectionBackground];
//
// Here I set an image based on the row. This is just to have something
// colorful to show on each row.
//
if ((row % 3) == 0)
{
cell.imageView.image = [UIImage imageNamed:#"imageA.png"];
}
else if ((row % 3) == 1)
{
cell.imageView.image = [UIImage imageNamed:#"imageB.png"];
}
else
{
cell.imageView.image = [UIImage imageNamed:#"imageC.png"];
}
#else
cell.text = [NSString stringWithFormat:#"Cell at row %ld.", [indexPath row]];
#endif
return cell;
}
past it after all #import lines
#define USE_CUSTOM_DRAWING 1
Heading ##Simplest way of changing alternate colors
if(indexPath.row%2) {
cell.backgroundColor=[UIColor nameUrColor] //brownColor, yellowColor, blueColor
} else {
cell.backgroundColor=[UIColor nameAnotherColor]
}
if(cell.contentView)
{
[cell.nameLbl setFont:[UIFont systemFontOfSize:24]];
int red_value = arc4random() % 210;
int green_value = arc4random() % 210;
int blue_value = arc4random() % 210;
cell.contentView.backgroundColor = [UIColor colorWithRed:red_value/255.0 green:green_value/255.0 blue:blue_value/255.0 alpha:0.6];
}

Dealing with Core data one-to-many relationship

I have been beating my head over this issue for some time now and my last hope is Stack Overflow.
Here is the app idea. I have two entities modeled in core data. The Golfer entity has a one to many relationship with FittingSession, so each golfer is capable of having more than one fitting session. I am not able to post an image for the data models as I am a new user.
But here are the details:
ENTITY: GOLFER and FITTING SESSION
Attributes for Golfer - first_name, last_name, emailId, contactNum, picture
Relationship : NSSet * fittingSessions
Attributes for Fitting Sessions - session_number, date, location, notes.
Relationship: Golfer * whoPlayed
I am working on one view controller called ViewManager (kinda base view for all my classes) and it has 2-3 Custom UIViews inside it. I animate them in and out whenever I need them.
I am getting my Golfers list-collection in a tableview from NSFetchedResultsController and getting the Fitting Sessions attributes in a tableview by the same technique using NSFetchedResultsController. My question is: How do I get a specific fitting session for a specific golfer? What do I have to write in TableViewDidSelectRow Method of Parent( Golfer )View? How do I deal with this one to many relationship? Here's my code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if(tableView == mGolferTblView)
{
NSInteger count = [[self.fetchedResultsController sections] count];
NSLog(#"count section GOLFER TABLE VIEW=%d", count);
return count;
}
else if(tableView == mFittingTblView)
{
return 1;
}
else {
}
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView == mGolferTblView)
{
id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
NSLog(#"count for array ROWS for GOLFERS =%d", [sectionInfo numberOfObjects]);
return [sectionInfo numberOfObjects];
}
else if(tableView == mFittingTblView)
{
mFittingSessionArray = [mFittingSessionSet allObjects];
NSLog(#"array here is=%#", mFittingSessionArray);
NSLog(#"count for ROWS in FITTING SESSIONS table view=%d", [mFittingSessionArray count]);
return [mFittingSessionArray count];
// id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fittingFetchedResultsController sections] objectAtIndex:section];
// NSLog(#"count for array ROWS for FITTING SESSIONS =%d", [sectionInfo numberOfObjects]);
// return [sectionInfo numberOfObjects];
}
else {
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == mGolferTblView)
{
static NSString *CellIdentifier = #"Cell";
static NSInteger fullNameTag = 1;
static NSInteger imageTag = 2;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
UILabel *fakeLbl =[[UILabel alloc] initWithFrame:CGRectMake(100, 30, 100, 30)];
fakeLbl.backgroundColor = [UIColor clearColor];
fakeLbl.textColor = [UIColor grayColor];
fakeLbl.text=#"3 days ago";
[cell.contentView addSubview:fakeLbl];
[fakeLbl release];
UIImageView *btnImage =[[UIImageView alloc] initWithFrame:CGRectMake(250, 40, 25, 28)];
btnImage.image = [UIImage imageNamed:#"badge_25x28.png"];
btnImage.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:btnImage];
[btnImage release];
UILabel *fullNameLbl =[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 300, 30)];
fullNameLbl.backgroundColor = [UIColor clearColor];
fullNameLbl.textColor = [UIColor whiteColor];
fullNameLbl.numberOfLines = 1;
fullNameLbl.adjustsFontSizeToFitWidth = YES;
fullNameLbl.tag = fullNameTag;
[cell.contentView addSubview:fullNameLbl];
[fullNameLbl release];
UIImageView *imageView =[[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 71, 91)];
imageView.backgroundColor = [UIColor clearColor];
imageView.tag = imageTag;
[cell.contentView addSubview:imageView];
[imageView release];
}
mGolfer = [self.fetchedResultsController objectAtIndexPath:indexPath];
UILabel * fullNameLbl = (UILabel *) [cell.contentView viewWithTag:fullNameTag];
fullNameLbl.text = mGolfer.fullName;
UIImageView * imgView = (UIImageView *) [cell.contentView viewWithTag:imageTag];
imgView.image = mGolfer.picture;
return cell;
}
if(tableView == mFittingTblView)
{
static NSString *CellIdentifier = #"Cell";
static NSInteger locationTag = 1;
static NSInteger notesTag = 2;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
UIImageView *iconImage =[[UIImageView alloc] initWithFrame:CGRectMake(10, 40, 11, 18)];
iconImage.image = [UIImage imageNamed:#"icon_locationmarker_11x18.png"];
iconImage.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:iconImage];
[iconImage release];
UILabel *fakeDateLbl =[[UILabel alloc] initWithFrame:CGRectMake(180, 15, 100, 20)];
fakeDateLbl.backgroundColor = [UIColor clearColor];
fakeDateLbl.textColor = [UIColor grayColor];
fakeDateLbl.text=#"apr.30.2012";
[cell.contentView addSubview:fakeDateLbl];
[fakeDateLbl release];
UIImageView *fakeImage1 =[[UIImageView alloc] initWithFrame:CGRectMake(25, 90, 43, 43)];
fakeImage1.image = [UIImage imageNamed:#"icon_catDriver_43x43.png"];
fakeImage1.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:fakeImage1];
[fakeImage1 release];
UIImageView *fakeImage2 =[[UIImageView alloc] initWithFrame:CGRectMake(70, 90, 43, 43)];
fakeImage2.image = [UIImage imageNamed:#"icon_catFairway_43x43.png"];
fakeImage2.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:fakeImage2];
[fakeImage2 release];
UIImageView *fakeImage3 =[[UIImageView alloc] initWithFrame:CGRectMake(115, 90, 43, 43)];
fakeImage3.image = [UIImage imageNamed:#"icon_catHybrid_43x43.png"];
fakeImage3.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:fakeImage3];
[fakeImage3 release];
UIImageView *fakeImage4 =[[UIImageView alloc] initWithFrame:CGRectMake(160, 90, 43, 43)];
fakeImage4.image = [UIImage imageNamed:#"icon_catIron_43x43.png"];
fakeImage4.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:fakeImage4];
[fakeImage4 release];
UIImageView *fakeImage5 =[[UIImageView alloc] initWithFrame:CGRectMake(205, 90, 43, 43)];
fakeImage5.image = [UIImage imageNamed:#"icon_catWedge_43x43.png"];
fakeImage5.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:fakeImage5];
[fakeImage5 release];
UILabel *sessionLbl =[[UILabel alloc] initWithFrame:CGRectMake(10, 7, 150, 30)];
sessionLbl.backgroundColor = [UIColor clearColor];
sessionLbl.textColor = [UIColor redColor];
sessionLbl.text = #"session";
sessionLbl.font = [UIFont boldSystemFontOfSize:18];
[cell.contentView addSubview:sessionLbl];
[sessionLbl release];
UILabel *locationLbl =[[UILabel alloc] initWithFrame:CGRectMake(30, 32, 270, 30)];
locationLbl.backgroundColor = [UIColor clearColor];
locationLbl.textColor = [UIColor whiteColor];
locationLbl.tag = locationTag;
[cell.contentView addSubview:locationLbl];
[locationLbl release];
UILabel *notesLbl =[[UILabel alloc] initWithFrame:CGRectMake(30, 54, 270, 30)];
notesLbl.backgroundColor = [UIColor clearColor];
notesLbl.textColor = [UIColor whiteColor];
notesLbl.tag = notesTag;
[cell.contentView addSubview:notesLbl];
[notesLbl release];
}
mFittingSessionArray = [mFittingSessionSet allObjects];
mFittingSession = [mFittingSessionArray objectAtIndex:indexPath.row];
UILabel *locationLbl = (UILabel *)[cell.contentView viewWithTag:locationTag];
locationLbl.text = mFittingSession.locationUppercase;
NSLog(#"location=%#", mFittingSession.locationUppercase);
UILabel *notesLbl = (UILabel *)[cell.contentView viewWithTag:notesTag];
notesLbl.text = mFittingSession.notesInQuotes;
return cell;
}
return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == mGolferTblView)
{
mGolfer = (Golfer *)[self.fetchedResultsController objectAtIndexPath:indexPath];
mGolferNameLbl.text = mGolfer.fullName;
mGolferHeaderPicture.image = mGolfer.picture;
NSSet * fittingSessionSet = mGolfer.fittingSessions;
mFittingSessionArray = [fittingSessionSet allObjects];
NSLog(#"count for sessions=%d", [mFittingSessionArray count]);
NSLog(#"fiting sessions for golfer %# are= %#", mGolfer.first_name, mFittingSessionArray);
}
}
Also, this is how I add a new fitting session to a particular golfer:
- (IBAction)addNewSession:(id)sender
{
AppDelegate * applicationDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = [applicationDelegate managedObjectContext];
mFittingSession=(FittingSession*) [NSEntityDescription insertNewObjectForEntityForName:#"FittingSession" inManagedObjectContext:context];
mFittingSession.location=mLocationTextField.text;
mFittingSession.notes=mNotesTxtView.text;
**mFittingSession.whoPlayed = self.golfer;** This is setting the relationship (whoPlayed is inverse relation to golfer provided by core data)
}
Please help me in this as I am really not getting how to deal with the relationship in core data. Please provide some code or snippets so that I can know what's going on.
Thank you
Maybe I don't understand your question correctly, but to get a Golfer's Fitting Session is really easy. So in the first code block you just do the following:
mGolfer = (Golfer *)[self.fetchedResultsController objectAtIndexPath:indexPath];
NSSet *fittingSession = mGolfer.fittingSessions;
You can access the relations as you would access the other attributes.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if(tableView == mGolferTblView)
{
NSInteger count = [[self.fetchedResultsController sections] count];
NSLog(#"count section GOLFER TABLE VIEW=%d", count);
return count;
}
else if(tableView == mFittingTblView)
{
NSInteger countOfSections = 1;
NSLog(#"count section FITTING SESSION VIEW=%d", countOfSections);
return countOfSections;
}
else {
}
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView == mGolferTblView)
{
id<NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
NSLog(#"count for ROWS in GOLFERS table view =%d", [sectionInfo numberOfObjects]);
return [sectionInfo numberOfObjects];
}
else if(tableView == mFittingTblView)
{
mFittingSessionArray = [mFittingSessionSet allObjects];
NSLog(#"array here is=%#", mFittingSessionArray);
NSLog(#"count for ROWS in FITTING SESSIONS table view=%d", [mFittingSessionArray count]);
return [mFittingSessionArray count];
}
else {
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == mGolferTblView)
{
static NSString *CellIdentifier = #"Cell";
static NSInteger fullNameTag = 1;
static NSInteger imageTag = 2;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
UILabel *fullNameLbl =[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 300, 30)];
fullNameLbl.backgroundColor = [UIColor clearColor];
fullNameLbl.textColor = [UIColor whiteColor];
fullNameLbl.numberOfLines = 1;
fullNameLbl.adjustsFontSizeToFitWidth = YES;
fullNameLbl.tag = fullNameTag;
[cell.contentView addSubview:fullNameLbl];
[fullNameLbl release];
UIImageView *imageView =[[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 71, 91)];
imageView.backgroundColor = [UIColor clearColor];
imageView.tag = imageTag;
[cell.contentView addSubview:imageView];
[imageView release];
}
mGolfer = [self.fetchedResultsController objectAtIndexPath:indexPath];
UILabel * fullNameLbl = (UILabel *) [cell.contentView viewWithTag:fullNameTag];
fullNameLbl.text = mGolfer.fullName;
UIImageView * imgView = (UIImageView *) [cell.contentView viewWithTag:imageTag];
imgView.image = mGolfer.picture;
return cell;
}
else if(tableView == mFittingTblView)
{
**mFittingSessionArray = [mFittingSessionSet allObjects];** // Added this line
static NSString *CellIdentifier = #"Cell";
static NSInteger locationTag = 1;
static NSInteger notesTag = 2;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
UILabel *locationLbl =[[UILabel alloc] initWithFrame:CGRectMake(30, 32, 270, 30)];
locationLbl.backgroundColor = [UIColor clearColor];
locationLbl.textColor = [UIColor whiteColor];
locationLbl.tag = locationTag;
[cell.contentView addSubview:locationLbl];
[locationLbl release];
UILabel *notesLbl =[[UILabel alloc] initWithFrame:CGRectMake(30, 54, 270, 30)];
notesLbl.backgroundColor = [UIColor clearColor];
notesLbl.textColor = [UIColor whiteColor];
notesLbl.tag = notesTag;
[cell.contentView addSubview:notesLbl];
[notesLbl release];
}
mFittingSession = [mFittingSessionArray objectAtIndex:indexPath.row];
UILabel *locationLbl = (UILabel *)[cell.contentView viewWithTag:locationTag];
UILabel *notesLbl = (UILabel *)[cell.contentView viewWithTag:notesTag];
locationLbl.text = mFittingSession.locationUppercase;
notesLbl.text = mFittingSession.notesInQuotes;
return cell;
}
else {
}
return 0;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == mGolferTblView)
{
if(self.editing)
{
[self.golferTblView deselectRowAtIndexPath:indexPath animated:YES];
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut
animations:^ {
mEditGolfersView.hidden = NO;
mEditGolfersView.frame = CGRectMake(305, mEditGolfersView.frame.origin.y, mEditGolfersView.frame.size.width, mEditGolfersView.frame.size.height);
}
completion:NULL];
mGolfer = (Golfer *) [self.fetchedResultsController objectAtIndexPath:indexPath];
mEditFirstName.text = mGolfer.first_name;
mEditMiddleName.text = mGolfer.middle_name;
mEditLastName.text = mGolfer.last_name;
mEditEmailField.text = mGolfer.email_id;
mEditContactNum.text = mGolfer.contactNumber;
mEditPictureView.image = mGolfer.picture;
mShowDataBtn.enabled = NO;
return;
}
[self.golferTblView deselectRowAtIndexPath:indexPath animated:YES];
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseOut
animations:^ {
mGolfersView.frame = CGRectMake(-260, mGolfersView.frame.origin.y, mGolfersView.frame.size.width, mGolfersView.frame.size.height);
}
completion:^(BOOL finished){
mGolfersView.hidden = YES;
}];
[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseIn
animations:^ {
mFittingSessionView.hidden = NO;
mFittingSessionView.frame = CGRectMake(-19, mFittingSessionView.frame.origin.y, mFittingSessionView.frame.size.width, mFittingSessionView.frame.size.height);
}
completion:NULL];
mGolfer = (Golfer *)[self.fetchedResultsController objectAtIndexPath:indexPath];
mGolferNameLbl.text = mGolfer.fullName;
mGolferHeaderPicture.image = mGolfer.picture;
mFittingSessionSet = mGolfer.fittingSessions;
mFittingSessionArray = [mFittingSessionSet allObjects];
NSLog(#"count for sessions=%d", [mFittingSessionArray count]);
NSLog(#"fiting sessions for golfer %# are= %#", mGolfer.first_name, mFittingSessionArray);
**[mFittingTblView reloadData];** // Added this and this reloads the data for fitting view.
}
}