cellForRowAtIndexPath and sizeToFit reduces label width when scrolling - ios

I've a custom cell with labels init in a UITableViewCell.
In my cellForRowAtIndexPath method after setting label content i call sizeToFit on the label to get the correct width and height, but when i scroll in my TableView, the label width reduce on each cells, every time i scroll.
Anyone for help ?
Thanks
My custom UITableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
CGRect viewBounds = self.contentView.bounds;
// marge
CGFloat margin = 20;
self.excuse_date = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 300, 30)];
self.excuse_date.textColor = [UIColor blackColor];
self.excuse_date.font = [UIFont fontWithName:#"Arial" size:12.0f];
[self addSubview:self.excuse_date];
static CGFloat dateWidth = 130;
self.excuse_date.frame = CGRectMake(viewBounds.size.width-dateWidth-35, margin, dateWidth, 20);
CGRect dateFrame = self.excuse_date.frame;
self.excuse_date.textAlignment = NSTextAlignmentRight;
// setup excuse_auteur
self.excuse_auteur = [[UILabel alloc] init];
self.excuse_auteur.font = [UIFont fontWithName:#"Helvetica" size:13];
self.excuse_auteur.textColor = [UIColor darkGrayColor];
self.excuse_auteur.textAlignment = NSTextAlignmentLeft;
self.excuse_auteur.frame = CGRectMake(margin, margin, viewBounds.size.width-dateWidth-(margin*2), 20);
[self addSubview:self.excuse_auteur];
// setup excuse_texte
self.excuse_texte = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(dateFrame)+margin/2, viewBounds.size.width - (margin*3), 200)];
self.excuse_texte.lineBreakMode = NSLineBreakByWordWrapping;
self.excuse_texte.numberOfLines = 0;
self.excuse_texte.font = [UIFont fontWithName:#"Helvetica" size:17];
self.excuse_texte.autoresizingMask = UIViewAutoresizingNone;
[self addSubview:self.excuse_texte];
CGRect textFrame = self.excuse_texte.frame;
// setup up image
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"up-small"]];
self.img = imageView;
[self addSubview:self.img];
imageView.frame = CGRectMake(20, CGRectGetMaxY(textFrame)+margin/2, 20, 20);
// setup up
self.up = [[UILabel alloc] initWithFrame:CGRectMake(45, CGRectGetMaxY(textFrame)+margin/2+2, viewBounds.size.width - margin*2, 20)];
self.up.font = [UIFont fontWithName:#"Helvetica" size:11];
self.up.textColor = [UIColor darkGrayColor];
self.up.textAlignment = NSTextAlignmentLeft;
[self addSubview:self.up];
}
return self;
}
My cellForRowAtIndexPath method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BBExcuse *excuse = [self.list objectAtIndex:indexPath.row];
static NSString *cellIdentifier = #"Cell";
// Similar to UITableViewCell, but
BBTableViewCell *cell = (BBTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[BBTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.excuse_texte.text = excuse.excuse_texte;
// #TODO problem here ?
[cell.excuse_texte sizeToFit];
cell.excuse_auteur.text = excuse.excuse_auteur;
cell.excuse_date.text = excuse.excuse_date;
cell.up.text = [NSString stringWithFormat:#"%#", excuse.up];
cell.img.frame = CGRectMake(20, CGRectGetMaxY(cell.excuse_texte.frame)+20/2, 20, 20);
cell.up.frame = CGRectMake(45, CGRectGetMaxY(cell.excuse_texte.frame)+20/2+2, 20, 20);
// setup up
return cell;
}

Ok solved by removing sizeToFit and specify height and width in cellForRowAtIndexPath
cell.excuse_texte.text = excuse.excuse_texte;
NSString *str = excuse.excuse_texte;
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont systemFontOfSize:17];
gettingSizeLabel.text = str;
gettingSizeLabel.numberOfLines = 0;
gettingSizeLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(260.0f, 9999.0f);
CGSize theSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
// on resize sans sizetofit
cell.excuse_texte.frame = CGRectMake(cell.excuse_texte.frame.origin.x, cell.excuse_texte.frame.origin.y, cell.excuse_texte.frame.size.width, theSize.height);

Related

How to do pagination in uitableview without using Api?

I am working on one project where i want to use pagination in uitableview without using api. I am having a nsdictionary and i kept that dictionary in an nsarray ,now i want that in a list view type there are 10,20,30 numbers and which number i select that amount of rows will display in UI.
I have done this in uitableview
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string1 = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string1];
if(!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string1];
UILabel *label1 = (UILabel*)[cell.contentView viewWithTag:401];
CGFloat widthLabelHeader = CGRectGetWidth(orderTable.frame)/7;
if(!label1)
{
label1 = [[UILabel alloc]init];
label1.frame = CGRectMake(0, 0, widthLabelHeader, 45);
label1.layer.borderWidth = 0.5;
label1.font = [UIFont fontWithName:#"ChalkboardSE-Bold" size:14];
[cell.contentView addSubview:label1];
}
label1.textAlignment = NSTextAlignmentCenter;
UILabel *label2 = (UILabel*)[cell.contentView viewWithTag:402];
if(!label2)
{
label2 = [[UILabel alloc]init];
label2.frame = CGRectMake(CGRectGetMaxX(label1.frame), 0, widthLabelHeader, 45);
label2.layer.borderWidth = 0.5;
label2.font = [UIFont fontWithName:#"ChalkboardSE-Bold" size:14];
[cell.contentView addSubview:label2];
}
label2.textAlignment = NSTextAlignmentCenter;
UILabel *label3 = (UILabel*)[cell.contentView viewWithTag:403];
if(!label3)
{
label3 = [[UILabel alloc]init];
label3.frame = CGRectMake(CGRectGetMaxX(label2.frame), 0, widthLabelHeader, 45);
label3.layer.borderWidth = 0.5;
label3.font = [UIFont fontWithName:#"ChalkboardSE-Bold" size:14];
[cell.contentView addSubview:label3];
}
label3.textAlignment = NSTextAlignmentCenter;
UILabel *label4 = (UILabel*)[cell.contentView viewWithTag:404];
if(!label4)
{
label4 = [[UILabel alloc]init];
label4.frame = CGRectMake(CGRectGetMaxX(label3.frame), 0, widthLabelHeader, 45);
label4.layer.borderWidth = 0.5;
label4.font = [UIFont fontWithName:#"ChalkboardSE-Bold" size:14];
[cell.contentView addSubview:label4];
}
label4.textAlignment = NSTextAlignmentCenter;
UILabel *label5 = (UILabel*)[cell.contentView viewWithTag:405];
if(!label5)
{
label5 = [[UILabel alloc]init];
label5.frame = CGRectMake(CGRectGetMaxX(label4.frame), 0, widthLabelHeader, 45);
label5.layer.borderWidth = 0.5;
label5.font = [UIFont fontWithName:#"ChalkboardSE-Bold" size:14];
[cell.contentView addSubview:label5];
}
label5.textAlignment = NSTextAlignmentCenter;
UILabel *label6 = (UILabel*)[cell.contentView viewWithTag:406];
if(!label6)
{
label6 = [[UILabel alloc]init];
label6.frame = CGRectMake(CGRectGetMaxX(label5.frame), 0, widthLabelHeader, 45);
label6.layer.borderWidth = 0.5;
label6.font = [UIFont fontWithName:#"ChalkboardSE-Bold" size:14];
[cell.contentView addSubview:label6];
}
label6.textAlignment = NSTextAlignmentCenter;
UILabel *label7 = (UILabel*)[cell.contentView viewWithTag:407];
if(!label7)
{
label7 = [[UILabel alloc]init];
label7.frame = CGRectMake(CGRectGetMaxX(label6.frame), 0, widthLabelHeader, 45);
label7.layer.borderWidth = 0.5;
label7.font = [UIFont fontWithName:#"ChalkboardSE-Bold" size:14];
[cell.contentView addSubview:label7];
}
label7.textAlignment = NSTextAlignmentCenter;
dict1 = [array1 objectAtIndex:indexPath.row];
if( dict1)
{
label1.text = [dict1 objectForKey:#"key1" ];
label1.backgroundColor = [UIColor lightGrayColor];
label2.text = [dict1 objectForKey:#"key2" ];
label2.backgroundColor = [UIColor lightGrayColor];
label3.text = [dict1 objectForKey:#"key3" ];
label3.backgroundColor = [UIColor lightGrayColor];
label4.text = [dict1 objectForKey:#"key4" ];
label4.backgroundColor = [UIColor lightGrayColor];
label5.text = [dict1 objectForKey:#"key5" ];
label5.backgroundColor = [UIColor lightGrayColor];
label6.text = [dict1 objectForKey:#"key6" ];
label6.backgroundColor = [UIColor lightGrayColor];
label7.text = [dict1 objectForKey:#"key7" ];
label7.backgroundColor = [UIColor lightGrayColor];
}}
return cell;
}
Please Help me how to do this?
use this method is method and call Api and append in same array which used in table datasource
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
BOOL endOfTable = (scrollView.contentOffset.y >= ((showListingArray.count * 60) - scrollView.frame.size.height)); // Here 40 is row height
nextPage ++;
NSString *nextPageStr = [NSString stringWithFormat:#"%d", nextPage];
int totalpages = [[PaginnationDic objectForKey:#"totalPages"]intValue];
if ( endOfTable && !scrollView.dragging && !scrollView.decelerating)
{
if (nextPage >= totalpages) {
// NSLog(#"No More Page to load");
return;
}
objPCDetailTableView.tableFooterView = footerView;
NSDictionary *parametrs = #{#"movieid":_movieID, #"page":nextPageStr, #"cityId":[Utility getCityID]};
[self getMoviesDetailFromApi:parametrs];
[(UIActivityIndicatorView *)[footerView viewWithTag:10] startAnimating];
}
}
You should set this deleget method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
with number you entered in text field and make this call [tableView reloadData]
or use this delegate methods
- (void)insertRowsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
to insert just new rows into you tableView.

Variable UITableViewCell height not working

I'm trying to have a UITableView with variable cell heights. The height should be based on the height of an image fetched from the server. I'm having some difficulties though. This is the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CGFloat height = (0.5*(self.view.frame.size.width-10))+100;
UILabel *heightLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-35, 30)];
heightLabel.text = [self.streams[indexPath.row] excerpt];
heightLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:14];
heightLabel.numberOfLines = 3;
[heightLabel sizeToFit];
height = height + heightLabel.frame.size.height;
NSLog(#"Cell height is %f", height);
cell.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width-20, cell.frame.size.height-20)];
backgroundView.backgroundColor = [UIColor whiteColor];
backgroundView.tag = 1;
[cell addSubview:backgroundView];
NSURL *imageLink = [NSURL URLWithString:[self.streams[indexPath.row] image]];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width-20, 0.5*(self.view.frame.size.width-10))];
__block UIActivityIndicatorView *activityIndicator;
__weak UIImageView *weakImageView = imageView;
imageView.tag = 2;
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.clipsToBounds = YES;
[cell addSubview:imageView];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, imageView.frame.origin.y + imageView.frame.size.height + 10, self.view.frame.size.width-35, 30)];
nameLabel.text = [self.streams[indexPath.row] name];
nameLabel.textColor = [UIColor blackColor];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.font = [UIFont fontWithName:#"HelveticaNeue-Medium" size:16];
nameLabel.numberOfLines = 2;
[nameLabel sizeToFit];
nameLabel.tag = 3;
[cell addSubview:nameLabel];
UILabel *descLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, nameLabel.frame.origin.y + nameLabel.frame.size.height + 5, self.view.frame.size.width-35, 30)];
descLabel.text = [NSString stringWithFormat:#"Posted by %#", [self.streams[indexPath.row] author]];
descLabel.textColor = [UIColor colorWithRed:193.0/255.0 green:193.0/255.0 blue:193.0/255.0 alpha:1.0];
descLabel.textAlignment = NSTextAlignmentLeft;
descLabel.font = [UIFont fontWithName:#"HelveticaNeue-Medium" size:12];
descLabel.numberOfLines = 2;
[descLabel sizeToFit];
descLabel.tag = 5;
[cell addSubview:descLabel];
UILabel *websiteLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, descLabel.frame.origin.y + descLabel.frame.size.height + 5, self.view.frame.size.width-35, 30)];
websiteLabel.text = [self.streams[indexPath.row] excerpt];
websiteLabel.textColor = [UIColor colorWithRed:119.0/255.0 green:119.0/255.0 blue:119.0/255.0 alpha:1.0];
websiteLabel.textAlignment = NSTextAlignmentLeft;
websiteLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:14];
websiteLabel.numberOfLines = 3;
[websiteLabel sizeToFit];
websiteLabel.tag = 4;
[cell addSubview:websiteLabel];
[imageView sd_setImageWithURL: imageLink
placeholderImage:[UIImage imageNamed:#"default.png"]
options:SDWebImageProgressiveDownload
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
if (!activityIndicator) {
[weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
activityIndicator.center = weakImageView.center;
[activityIndicator startAnimating];
}
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image) {
float newHeight;
#try {
[activityIndicator removeFromSuperview];
activityIndicator = nil;
float oldWidth = image.size.width;
float scaleFactor = imageView.frame.size.width / oldWidth;
newHeight = image.size.height * scaleFactor;
}
#catch (NSException *exception) {
newHeight = 0.5*(self.view.frame.size.width-10);
}
#finally {
imageView.image = image;
imageView.frame = CGRectMake(10, 10, self.view.frame.size.width-20, newHeight);
nameLabel.frame = CGRectMake(15, imageView.frame.origin.y + newHeight + 10, self.view.frame.size.width-35, 30);
[nameLabel sizeToFit];
descLabel.frame = CGRectMake(15, nameLabel.frame.origin.y + nameLabel.frame.size.height + 5, self.view.frame.size.width-35, 30);
[descLabel sizeToFit];
websiteLabel.frame = CGRectMake(15, descLabel.frame.origin.y + descLabel.frame.size.height + 5, self.view.frame.size.width-35, 30);
[websiteLabel sizeToFit];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self.tableView beginUpdates];
[cell setFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, newHeight+nameLabel.frame.size.height+descLabel.frame.size.height+websiteLabel.frame.size.height+50)];
[self.tableView endUpdates];
backgroundView.frame = CGRectMake(10, 10, self.view.frame.size.width-20, newHeight+nameLabel.frame.size.height+descLabel.frame.size.height+websiteLabel.frame.size.height+25);
}
}
}];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100.0f;
}
What am I doing wrong? Currently, cells are overlapping....
If your cells has variable height you should set AutomaticDimension
in viewDidLoad set this:
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 100
and you can eliminate heightForRowAtIndexPath or set it to automatic
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension; //works only about iOS 8
}

IOS, How to set Auto Layout in your UITableViewCell that contains different Subviews

I have a layout issue, i have a UIView that contains an UIImageView and three other UILabels. The part that needs to set the layout dynamically is the main UIView thats added to the cell and a UILabel that will contain text of any length lets say for this example.
What i have done i created a custom UITableViewCell and added the SubViews to the custom UITableViewCell, like here:
-(void)setupView:(PostInfo*)postInfo{
CGRect screenRect = [[UIScreen mainScreen] bounds];
viewPostMessage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, screenRect.size.width - 20, 100)];
viewPostMessage.backgroundColor = [UIColor colorWithRed:193.0f/255 green:193.0f/255 blue:193.0f/255 alpha:1.0f];
viewPostMessage.layer.borderColor = [UIColor blackColor].CGColor;
viewPostMessage.layer.borderWidth = 0.5f;
if(postInfo.userImage.length > 0){
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
UIImage *imageUser = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://www.hugt.co.uk/userimage/%d/userImage.jpg", postInfo.userId]]]];
userImage.image = imageUser;
[viewPostMessage addSubview:userImage];
}else{
UIView *viewImage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
viewImage.backgroundColor = [UIColor colorWithRed:132.0f/255 green:132.0f/255 blue:132.0f/255 alpha:1.0f];
[viewPostMessage addSubview:viewImage];
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
UIImage *imageUser = [UIImage imageNamed:#"defaultuser.jpg"];
userImage.image = imageUser;
[viewImage addSubview:userImage];
}
labelUserName = [[UILabel alloc] initWithFrame:CGRectMake(50, 8, 200, 16)];
labelUserName.textColor = [UIColor colorWithRed:56.0f/255 green:56.0f/255 blue:57.0f/255 alpha:1.0f];
labelUserName.text = [NSString stringWithFormat:#"%# %# posted...", postInfo.firstName,postInfo.lastName];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelUserName.font = [UIFont fontWithName:#"Helvetica" size:12];
labelUserName.userInteractionEnabled = YES;
[viewPostMessage addSubview:labelUserName];
labelCreated = [[UILabel alloc] initWithFrame:CGRectMake(50, 24, 200, 16)];
labelCreated.textColor = [UIColor colorWithRed:86.0f/255 green:152.0f/255 blue:179.0f/255 alpha:1.0f];
labelCreated.text = [NSDateFormatter localizedStringFromDate:postInfo.timeStampCreated dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"AM" withString:#""];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"PM" withString:#""];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelCreated.font = [UIFont fontWithName:#"Helvetica" size:12];
labelCreated.userInteractionEnabled = YES;
[viewPostMessage addSubview:labelCreated];
labelMessage = [[UILabel alloc] initWithFrame:CGRectMake(50, 43, 210, 50)];
labelMessage.textColor = [UIColor colorWithRed:141.0f/255 green:142.0f/255 blue:142.0f/255 alpha:1.0f];
labelMessage.text = postInfo.message;
labelMessage.numberOfLines = 3;
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelMessage.font = [UIFont fontWithName:#"Helvetica" size:12];
labelMessage.userInteractionEnabled = YES;
[labelMessage sizeToFit];
[viewPostMessage addSubview:labelMessage];
[self.contentView addSubview:viewPostMessage];
}
When i create this custom UITableViewCell i pass in an object that sets the text on the UILabels, like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cell";
if(tableViewThreads == tableView){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
ThreadInfo *threadInfo = (ThreadInfo*)[self.threadsArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:[self setupThreadItem:threadInfo]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
if(tableViewPosts == tableView){
PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
PostInfo *postInfo = (PostInfo*)[self.postsArray objectAtIndex:indexPath.row];
[cell setupView:postInfo];
//[cell addSubview:[self setupPostItem:postInfo]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
//[cell.contentView addSubview:[self setupThreadItem:threadInfo]];
}
return nil;
}
I have searched the web and also here to find out how to Auto Layout the Subviews in the cell but can't seem to understand what needs to go next. I read that you need a Prototype Cell so i created a custom UITableViewCell and thats how far I've got.
Any help would be appreciated, thanks.
So far i have got the cells to resize with Auto Layout but i have removed the UIView that sits inside the cell, so now i have three UILabels and an UIImageView which are the UIImageView (userImage), UILabel (labelUsername), UILabel (labelCreated) and UILabel (labelMessage). So the dimensions and coordinates are the same just that the UIView has been removed:
First i set up NSLayoutContsraints in my Custom Cell, code bellow:
Set numberOFLines = 0 and remove sizeToFit on the UILabel thats going to AutoLayout.
-(void)setupView:(PostInfo*)postInfo{
CGRect screenRect = [[UIScreen mainScreen] bounds];
viewPostMessage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, screenRect.size.width - 20, 100)];
viewPostMessage.backgroundColor = [UIColor colorWithRed:193.0f/255 green:193.0f/255 blue:193.0f/255 alpha:1.0f];
viewPostMessage.layer.borderColor = [UIColor blackColor].CGColor;
viewPostMessage.layer.borderWidth = 0.5f;
if(postInfo.userImage.length > 0){
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
UIImage *imageUser = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: [NSString stringWithFormat:#"http://www.hugt.co.uk/userimage/%d/userImage.jpg", postInfo.userId]]]];
userImage.image = imageUser;
[self.contentView addSubview:userImage];
}else{
UIView *viewImage = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 30, 30)];
viewImage.backgroundColor = [UIColor colorWithRed:132.0f/255 green:132.0f/255 blue:132.0f/255 alpha:1.0f];
[self.contentView addSubview:viewImage];
userImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
UIImage *imageUser = [UIImage imageNamed:#"defaultuser.jpg"];
userImage.image = imageUser;
[viewImage addSubview:userImage];
}
labelUserName = [[UILabel alloc] initWithFrame:CGRectMake(50, 8, 200, 16)];
labelUserName.textColor = [UIColor colorWithRed:56.0f/255 green:56.0f/255 blue:57.0f/255 alpha:1.0f];
labelUserName.text = [NSString stringWithFormat:#"%# %# posted...", postInfo.firstName,postInfo.lastName];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelUserName.font = [UIFont fontWithName:#"Helvetica" size:12];
labelUserName.userInteractionEnabled = YES;
[self.contentView addSubview:labelUserName];
labelCreated = [[UILabel alloc] initWithFrame:CGRectMake(50, 24, 200, 16)];
labelCreated.textColor = [UIColor colorWithRed:86.0f/255 green:152.0f/255 blue:179.0f/255 alpha:1.0f];
labelCreated.text = [NSDateFormatter localizedStringFromDate:postInfo.timeStampCreated dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"AM" withString:#""];
labelCreated.text = [labelCreated.text stringByReplacingOccurrencesOfString:#"PM" withString:#""];
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelCreated.font = [UIFont fontWithName:#"Helvetica" size:12];
labelCreated.userInteractionEnabled = YES;
[self.contentView addSubview:labelCreated];
labelMessage = [[UILabel alloc] initWithFrame:CGRectMake(50, 43, 210, 50)];
labelMessage.textColor = [UIColor colorWithRed:141.0f/255 green:142.0f/255 blue:142.0f/255 alpha:1.0f];
labelMessage.text = postInfo.message;
labelMessage.numberOfLines = 0;
//labelFirstName.textAlignment = NSTextAlignmentCenter;
labelMessage.font = [UIFont fontWithName:#"Helvetica" size:12];
labelMessage.userInteractionEnabled = YES;
labelMessage.lineBreakMode = NSLineBreakByWordWrapping;
//[labelMessage sizeToFit];
[self.contentView addSubview:labelMessage];
labelMessage.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-10-[bodyLabel]-19-|" options:0 metrics:nil views:#{ #"bodyLabel": labelMessage }]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|-43-[bodyLabel]-6-|" options:0 metrics:nil views:#{ #"bodyLabel": labelMessage }]];
//[self.contentView addSubview:viewPostMessage];
}
Then in my ViewController that contains the UITableVIew, i modified this bit of code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"cell";
if(tableViewThreads == tableView){
return 122;
}
if(tableViewPosts == tableView){
PostTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[PostTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
PostInfo *postInfo = (PostInfo*)[self.postsArray objectAtIndex:indexPath.row];
[cell setupView:postInfo];
[cell setNeedsLayout];
[cell layoutIfNeeded];
CGFloat h = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return h + 1;
}
return 0;
}
The Cells do now resize and the UILabel resizes automatically now but my other problem is that the UITableView scroll is not smooth so ill have to fix that, and when i scroll in the UITableView the Cell data from the UILabel (labelMessage) seems to print it self in other cells, don't know why this is
BUT the Cells resize and the other issues ill ask another question on here.
Sorry forgot to add this bit of code that sits in the PostTableViewCell:
- (void)layoutSubviews
{
[super layoutSubviews];
// Make sure the contentView does a layout pass here so that its subviews have their frames set, which we
// need to use to set the preferredMaxLayoutWidth below.
[self.contentView setNeedsLayout];
[self.contentView layoutIfNeeded];
// Set the preferredMaxLayoutWidth of the mutli-line bodyLabel based on the evaluated width of the label's frame,
// as this will allow the text to wrap correctly, and as a result allow the label to take on the correct height.
labelMessage.preferredMaxLayoutWidth = CGRectGetWidth(labelMessage.frame);
}

Adjusting Cell fields - Objective C

I have a dynamically set table view controller that is used to populate a news type feed. I am having trouble connecting one class to the other for setting the text, image, etc... of that current cell.
Here is the gist:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"timelineCell";
FBGTimelineCell *cell = (FBGTimelineCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.text = [self.googlePlacesArrayFromAFNetworking[indexPath.row] objectForKey:#"message"]; <!-- here is where I want to for example, set the title to the message within this array.
if (!cell)
{
cell = [[FBGTimelineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell initTimelineCell];
}
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:#"%d.jpg", indexPath.row]];
cell.photoView.image = img;
return cell;
}
Here is the FBH... init function:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
cellContentView = [[UIView alloc] initWithFrame:CGRectMake(10, 5, 300, 440)];
cellContentView.backgroundColor = [UIColor whiteColor];
photoView = [[FBGTimelinePhotoView alloc] initWithFrame:CGRectMake(5, 102, 310, 310)];
photoView.backgroundColor = [UIColor darkGrayColor];
[photoView setUserInteractionEnabled:YES];
UIView *profilePic = [[UIView alloc] initWithFrame:CGRectMake(9, 9, 30, 30)];
profilePic.backgroundColor = [UIColor darkGrayColor];
UILabel *usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 9, 222, 18)];
usernameLabel.font = [UIFont systemFontOfSize:14.0];
usernameLabel.text = #"Username";
UILabel *timestampLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 25, 222, 17)];
timestampLabel.font = [UIFont systemFontOfSize:12.0];
timestampLabel.text = #"3 hours ago";
timestampLabel.textColor = [UIColor lightGrayColor];
UILabel *statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(9, 50, 283, 41)];
statusLabel.font = [UIFont systemFontOfSize:15.0];
statusLabel.text = #"Status..status..status..status..status..status..status..status..status..status..status..status..status..status..status..";
statusLabel.numberOfLines = 2;
statusLabel.lineBreakMode = NSLineBreakByWordWrapping;
UILabel *likeLabel = [[UILabel alloc] initWithFrame:CGRectMake(9, 413, 32, 21)];
likeLabel.font = [UIFont systemFontOfSize:13.0];
likeLabel.text = #"Like";
UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(113, 413, 74, 21)];
commentLabel.font = [UIFont systemFontOfSize:13.0];
commentLabel.text = #"Comment";
UILabel *shareLabel = [[UILabel alloc] initWithFrame:CGRectMake(246, 413, 46, 21)];
shareLabel.font = [UIFont systemFontOfSize:13.0];
shareLabel.text = #"Share";
[self addSubview:cellContentView];
[self addSubview:photoView];
[cellContentView addSubview:profilePic];
[cellContentView addSubview:usernameLabel];
[cellContentView addSubview:timestampLabel];
[cellContentView addSubview:statusLabel];
[cellContentView addSubview:likeLabel];
[cellContentView addSubview:commentLabel];
[cellContentView addSubview:shareLabel];
}
return self;
}
So I need to be able to set the cell text and different views within the cell within the cellForRowAtIndexPath if possible for each cell that is set up in the FB..init function.
Suggestions, thoughts?
You should create properties (in the FBGTimelineCell class) for each of the UI elements that you need to access in cellFroRowAtIndexPath, then you can access them with cell.propertyName.
You can create properties for all the dynamic values which are expected to be changed with each cell. Those properties you can set in your cellForRowAtIndexPath method.
eg. cell.statusText = [NSString stringWithFormat:#"%# is rocking!!", indexPath.row];
Public properties like statusText you can add all the UIElements expecting to be dynamically added.
Hope it helps.
Cheers.

Slow loading tableview on iPhone with reusable cells

I load the data from Parse.com backend, they send me a solutions for use the reusable cells but now I still have troubles with the loading speed, this is the coding I have in my tableview and I have a Subclass for making up my cells (ExploreStreamCustomCell.m)
- (ExploreStreamCustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
object:(PFObject *)object
{
static NSString *CellIdentifier = #"ExploreStreamCustomCell";
ExploreStreamCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ExploreStreamCustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
// Configure the cell
cell.listItemTitle.text = [object objectForKey:#"text"];
cell.checkinsLabel.text = [NSString stringWithFormat:#"%#", [object objectForKey:#"checkins"]];
cell.descriptionLabel.text = [object objectForKey:#"description"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
PFFile *listThumbnail = [object objectForKey:#"header"];
cell.listViewImage.image = [UIImage imageNamed:#"loading_image_stream.png"]; // placeholder image
cell.listViewImage.file = listThumbnail;
[cell.listViewImage loadInBackground:NULL];
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForNextPageAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [super tableView:tableView cellForNextPageAtIndexPath:indexPath];
cell.textLabel.font = [cell.textLabel.font fontWithSize:kPAWWallPostTableViewFontSize];
return cell;
}
If I have all the content of the //configure cell in the cell == nil the it's fast but it show up 3 of the 9 unique datarows and repeat those 3 unique content cell 3 times?
Edit extra code within ExploreStreamCustomCell.m
#import "ExploreStreamCustomCell.h"
#implementation ExploreStreamCustomCell
#synthesize listViewImage,
iconLocation,
iconPeople,
iconCheckins,
listItemTitle,
locationLabel,
peopleLabel,
checkinsLabel,
descriptionLabel,
listItemView;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
//Initialization code
listItemView = [[UIView alloc] init];
listViewImage = [[PFImageView alloc] init];
iconLocation = [[UIImageView alloc] init];
iconPeople = [[UIImageView alloc] init];
iconCheckins = [[UIImageView alloc] init];
listItemTitle = [[UILabel alloc] init];
locationLabel = [[UILabel alloc] init];
peopleLabel = [[UILabel alloc] init];
checkinsLabel = [[UILabel alloc] init];
descriptionLabel = [[UILabel alloc] init];
listViewImage.image = [UIImage imageNamed:#"nachtwacht_list_formaat.png"];
iconLocation.image = [UIImage imageNamed:#"icon_magenta_location.png"];
iconPeople.image = [UIImage imageNamed:#"icon_magenta_people.png"];
iconCheckins.image = [UIImage imageNamed:#"icon_magenta_checkins.png"];
listItemTitle.text = #"text";
locationLabel.text = #"0,7 km";
peopleLabel.text = #"34";
checkinsLabel.text = #"61";
descriptionLabel.text = #"Description text.";
[self.contentView addSubview:listItemView];
[self.contentView addSubview:listViewImage];
[self.contentView addSubview:iconLocation];
[self.contentView addSubview:iconPeople];
[self.contentView addSubview:iconCheckins];
[self.contentView addSubview:listItemTitle];
[self.contentView addSubview:locationLabel];
[self.contentView addSubview:peopleLabel];
[self.contentView addSubview:checkinsLabel];
[self.contentView addSubview:descriptionLabel];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+0 , 33, 280, 124);
listViewImage.frame = frame;
listViewImage.contentMode = UIViewContentModeScaleAspectFill;
listViewImage.layer.masksToBounds = YES;
//listViewImage.backgroundColor = [UIColor lightGrayColor];
frame= CGRectMake(boundsX+20 , 164, 12, 18);
iconLocation.frame = frame;
//iconLocation.backgroundColor = [UIColor lightGrayColor];
frame= CGRectMake(boundsX+102 , 164, 24, 18);
iconPeople.frame = frame;
//iconPeople.backgroundColor = [UIColor lightGrayColor];
frame= CGRectMake(boundsX+193 , 164, 20, 16);
iconCheckins.frame = frame;
//iconLocation.backgroundColor = [UIColor lightGrayColor];
frame= CGRectMake(boundsX+0 , 0, 280, 33);
listItemView.frame = frame;
listItemView.backgroundColor = [UIColor colorWithRed:0.749 green:0.000 blue:0.243 alpha:1.000];
frame= CGRectMake(boundsX+20 , 3, 240, 29);
listItemTitle.frame = frame;
//listItemTitle.textColor = [UIColor colorWithRed:250.0f/255.0f green:194.0f/255.0f blue:9.0f/255.0f alpha:0.8f];
listItemTitle.textAlignment = UITextAlignmentLeft;
listItemTitle.font = [UIFont boldSystemFontOfSize:15];
listItemTitle.textColor = [UIColor whiteColor];
listItemTitle.backgroundColor = [UIColor clearColor];
listItemTitle.lineBreakMode = UILineBreakModeTailTruncation;
//listItemTitle.backgroundColor = [UIColor orangeColor];
frame= CGRectMake(boundsX+40 , 164, 57, 21);
locationLabel.frame = frame;
locationLabel.textAlignment = UITextAlignmentLeft;
locationLabel.font = [UIFont boldSystemFontOfSize:12];
locationLabel.textColor = [UIColor colorWithRed:0.749 green:0.000 blue:0.243 alpha:1.000];
locationLabel.backgroundColor = [UIColor clearColor];
locationLabel.lineBreakMode = UILineBreakModeTailTruncation;
locationLabel.numberOfLines = 1;
//locationLabel.backgroundColor = [UIColor redColor];
frame= CGRectMake(boundsX+134 , 164, 57, 21);
peopleLabel.frame = frame;
peopleLabel.textAlignment = UITextAlignmentLeft;
peopleLabel.font = [UIFont boldSystemFontOfSize:12];
peopleLabel.textColor = [UIColor colorWithRed:0.749 green:0.000 blue:0.243 alpha:1.000];
peopleLabel.backgroundColor = [UIColor clearColor];
peopleLabel.lineBreakMode = UILineBreakModeTailTruncation;
peopleLabel.numberOfLines = 1;
frame= CGRectMake(boundsX+221 , 164, 51, 21);
checkinsLabel.frame = frame;
checkinsLabel.textAlignment = UITextAlignmentLeft;
checkinsLabel.font = [UIFont boldSystemFontOfSize:12];
checkinsLabel.textColor = [UIColor colorWithRed:0.749 green:0.000 blue:0.243 alpha:1.000];
checkinsLabel.backgroundColor = [UIColor clearColor];
checkinsLabel.lineBreakMode = UILineBreakModeTailTruncation;
checkinsLabel.numberOfLines = 1;
frame= CGRectMake(boundsX+0 , 189, 280, 55);
descriptionLabel.frame = frame;
descriptionLabel.textAlignment = UITextAlignmentLeft;
descriptionLabel.font = [UIFont systemFontOfSize:13];
descriptionLabel.backgroundColor = [UIColor clearColor];
descriptionLabel.lineBreakMode = UILineBreakModeTailTruncation;
descriptionLabel.numberOfLines = 3;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
/*
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#end
A great way to explore the inefficiencies of your code is to use Instruments' Time Profiler tool. The Time Profiler will let you see how much time is being spent on each task, line-by-line in your code.
I would recommend the following settings for profiling:
From Apple's Face Detection sample app:
You can then double click any line (higher percentages mean more time is being devoted to that method call) to see in the code how much time is spent in each place.
From here you can begin to figure out where you are being inefficient and see exactly what is taking up so much time. Good luck!

Resources