I have a UITextView inside a UITableCell i wanted to make it height dynamic according to it's size. So i have used the following code.
- (void)textViewDidChange:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
}
This code works just fine but the issue is my UITextView height becomes dynamic only when i scroll otherwise on load of UITableView it does not become dynamic height.Although method is called twice.Please tell me why this happend?
EDIT:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cell for row called %d",(int)[arr_post count]);
//define variables here
NSMutableAttributedString *mutableAttributeStr;
NSAttributedString *attributeStr;
static NSString *CellIdentifier = #"homeCell";
HomeCell *cell = [self.table_view
dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//get the post data
Post *user_post=[arr_post objectAtIndex:indexPath.row];
//set the button tags
cell.btn_like.tag=indexPath.row;
cell.btn_comment.tag=indexPath.row;
cell.btn_fav.tag=indexPath.row;
cell.btn_con.tag=indexPath.row;
cell.btn_book.tag=indexPath.row;
//add info to buttons
cell.btn_like.selected=user_post.isPostLiked;
cell.btn_comment.selected=user_post.isPostCommented;
cell.btn_fav.selected=user_post.isPostFavourite;
cell.btn_con.selected=user_post.isPostCondolence;
cell.btn_book.selected=user_post.isPostBookmarked;
//add text view path
//add user info
cell.label_name.text=user_post.username;
[cell.img_profile setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.user_profileImage]]placeholderImage:[UIImage imageNamed:#"post_placeholder.png"]];
//add location
if([user_post.location isEqualToString:#"Not Available"])
{
[cell.img_icon_location setHidden:true];
[cell.label_location setHidden:true];
}
else
{
cell.label_location.text=user_post.location;
}
//ad post info
cell.tv_post.text=user_post.post_description;
cell.tv_post.font = [UIFont fontWithName:user_post.font_family size:[user_post.font_size floatValue]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [formatter dateFromString:user_post.modification_date];
if([user_post.post_image isEqualToString:#"none"] && [user_post.post_video isEqualToString:#"none"])
{
}
else
{
UIBezierPath * imgRect = [UIBezierPath bezierPathWithRect:CGRectMake(0, 10, 100, 100)];
cell.tv_post.textContainer.exclusionPaths = #[imgRect];
UIImageView *tv_image =[[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 100, 100)];
[tv_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_post.post_video_thumbnail]]placeholderImage:[UIImage imageNamed:#"post_placeholder.png"]];
[cell.tv_post addSubview:tv_image];
}
//make textview height dynamic
cell.tv_post.scrollEnabled=NO;
[self textViewDidChange:cell.tv_post];
NSLog(#"textview height is %f",cell.tv_post.frame.size.height);
NSLog(#"main view height is %f",cell.view_tvContainer.frame.size.height);
//set the border of uiview
cell.view_tvContainer.layer.borderColor = [UIColor blackColor].CGColor;
cell.view_tvContainer.layer.borderWidth = 2.0f;
//set the like count
NSString *first_like_user=user_post.recent_like_name;
int count=(int)[first_like_user length];
int like_count=[user_post.like_count intValue];
//chek if tehre are any likes on the post
NSLog(#"post id is %#",user_post.id);
NSLog(#"recent like name is %#",user_post.recent_like_name);
NSLog(#"like count is %d",like_count);
if(like_count>0)
{
NSLog(#"inside like count block");
cell.label_like_count.lineBreakMode=NSLineBreakByWordWrapping;
[cell.label_like_count sizeToFit];
[cell.label_like_count setHidden:false];
NSString *str_like_count=[NSString stringWithFormat:#"%lu",(unsigned long)like_count-1];
if(like_count==1)
{
if([myUsername isEqualToString:first_like_user])
{
first_like_user=#"You asjlike sdfsdfsd sfd ";
count=3;
}
else
{
first_like_user=[first_like_user stringByAppendingString:#" like this post"];
}
}
else if(like_count==2)
{
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" other like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
else
{
if(like_count>1000)
{
like_count=like_count/1000;
str_like_count=[NSString stringWithFormat:#"%lu",(unsigned long)like_count];
str_like_count=[str_like_count stringByAppendingString:#"k"];
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" others like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
else
{
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" others like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
}
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.label_like_count setAttributedText:mutableAttributeStr];
}
else
{
NSLog(#"not inside like count");
[cell.label_like_count setHidden:true];
}
// show dynamic comment
NSMutableArray *user_comments=user_post.comments;
float comment_count=[user_post.comment_count intValue];
NSLog(#"post id is %#",user_post.id);
NSLog(#"arr comments count is %lu",(unsigned long)comment_count);
NSLog(#"arr user comments count is %lu",[user_comments count]);
if(comment_count>0)
{
NSLog(#"post id is %#",user_post.id);
//make label multiline
cell.first_comment.lineBreakMode=NSLineBreakByWordWrapping;
[cell.first_comment sizeToFit];
cell.second_cmment.lineBreakMode=NSLineBreakByWordWrapping;
[cell.second_cmment sizeToFit];
cell.third_comment.lineBreakMode=NSLineBreakByWordWrapping;
[cell.third_comment sizeToFit];
NSMutableAttributedString *mutableAttributeStr;
NSAttributedString *attributeStr;
if(comment_count==1)
{
[cell.first_comment setHidden:false];
[cell.second_cmment setHidden:true];
[cell.third_comment setHidden:true];
}
else if(comment_count==2)
{
[cell.first_comment setHidden:false];
[cell.second_cmment setHidden:false];
[cell.third_comment setHidden:true];
}
else
{
[cell.first_comment setHidden:false];
[cell.second_cmment setHidden:false];
[cell.third_comment setHidden:false];
[cell.btn_more_comments setHidden:false];
}
for(l=0;l<[user_comments count];l++)
{
NSLog(#"inside loop %d",l);
Comment *comment=[user_comments objectAtIndex:l];
NSLog(#"comment is %#",comment.comment);
NSLog(#"comment user is %#",comment.user_name);
if(l==0)
{
NSLog(#"l is zero");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
NSLog(#"comment string is %#",comment_string);
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.first_comment setAttributedText:mutableAttributeStr];
}
else if(l==1)
{
NSLog(#"l is 1");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
NSLog(#"comment string is %#",comment_string);
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.second_cmment setAttributedText:mutableAttributeStr];
}
else if(l==2)
{
NSLog(#"l is 2");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.third_comment setAttributedText:mutableAttributeStr];
}
}
}
else
{
[cell.first_comment setHidden:true];
[cell.second_cmment setHidden:true];
[cell.third_comment setHidden:true];
[cell.btn_more_comments removeFromSuperview];
}
cell.label_time.text=[BaseController getTimestampForDate:date];
[arr_indexpath addObject:indexPath];
return cell;
}
try with this.
-(void)dynamicTextSize{
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(200, 300, 200, 30)];
textView.center = self.view.center;
[self.view addSubview:textView];
NSString *string = #"You long text here";
textView.text = string;
//UIFont *font = [UIFont fontWithName:#"Arial" size:16.0f];
NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:textView.font, NSFontAttributeName, nil];
textView.backgroundColor = [UIColor lightGrayColor];
CGRect frame = [textView.text boundingRectWithSize:CGSizeMake(textView.frame.size.width, 10000) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:attrDict context:nil];
CGRect mFrame = textView.frame;
mFrame.size.width = frame.size.width;
mFrame.size.height = frame.size.height;
textView.frame = mFrame;
//NSLog(#"frame2:%#",NSStringFromCGRect(textView.frame));
}
Try call [cell layoutIfNeeded];& replace self.table_view with tabelview.This may solve your issue
Related
I am bit trouble with setting attributed text to uilable which is defined in uitableview cell. I am setting attributed text in cellForRowAtIndexPath delegate method of uitableview but it does not affect on output. I just wanted text of uilabel will display as bold text.
My code is as follow:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MessagesTable *msgobject=[messages objectAtIndex:indexPath.row];
static NSString* cellIdentifier = #"messagingCellText";
TextTableViewCell *ccell = (TextTableViewCell*) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (ccell == nil)
{
ccell = [[TextTableViewCell alloc] initMessagingCellWithReuseIdentifier:cellIdentifier MessageType:msgobject.messageMediaType];
cell2.backgroundColor=[UIColor clearColor];
cell2.userInteractionEnabled=YES;
cell2.layer.shouldRasterize = YES;
cell2.layer.rasterizationScale = [UIScreen mainScreen].scale;
}
NSString *newString = "This is Bold, This is regular";
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc]initWithString:newString];
NSRange rangeOfSubstring = [newString rangeOfString:#"This is Bold"];
[attrStr addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"GandhiSans-Bold" size:16]
range:rangeOfSubstring];
ccell.messageLabel.attributedText = attrStr;
return ccell;
}
And my initMessagingCellWithReuseIdentifier: method is as follows:
-(id)initMessagingCellWithReuseIdentifier:(NSString*)reuseIdentifier MessageType:(NSString *)msgTypePara{
if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) {
/*Message-Label*/
self.messageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.messageLabel.backgroundColor = [UIColor clearColor];
//self.messageLabel.font = [UIFont systemFontOfSize:messageTextSize];
self.messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.messageLabel.numberOfLines = 0;
self.messageLabel.textColor=[UIColor blackColor];
self.messageLabel.textAlignment=NSTextAlignmentLeft;
//self.messageLabel.font=[UIFont preferredFontForTextStyle:UIFontTextStyleBody];
//self.messageLabel.font = [UIFont fontWithName:#"GandhiSans-regular" size:messageTextSize];
self.messageLabel.userInteractionEnabled=YES;
[self.messageLabel sizeToFit];
[self addSubview: self.messageLabel];
[self.contentView addSubview: self.messageView];
return self;
}
Try this:
NSMutableAttributedString *MylabelAttributes = [[NSMutableAttributedString alloc] initWithString:#"my test"];
[MylabelAttributes addAttribute:NSForegroundColorAttributeName value:[UIColor yourcolor] range:NSMakeRange(0,MylabelAttributes.length)];
[MylabelAttributes addAttribute:NSFontAttributeName
value:[UIFont boldSystemFontOfSize:19.0]
range:NSMakeRange(0,MylabelAttributes.length)];
self.yourlabel.attributedText=MylabelAttributes;
try this
and please replace it with your particular code and check is there any change happens
NSString *newString = #"This is Bold, This is regular";
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc]initWithString:newString];
NSRange rangeOfSubstring = [newString rangeOfString:#"This is Bold"];
[attrStr addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"TimesNewRomanPS-BoldMT" size:16]
range:rangeOfSubstring];
[attrStr addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:rangeOfSubstring];
I want to merge NSString and NSMutableAttributedString .
In below code i want to make self.txtSearch as custom bold size and color.
code -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
SearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SearchViewCell"];
AutoSuggestModel *autoSuggestModel = [self.autoSuggestArray objectAtIndex:indexPath.row];
if ([[autoSuggestModel type] isEqualToString:#"product"] || [[autoSuggestModel type] isEqualToString:#"category"]){
cell.lblText.text = [NSString stringWithFormat:#"%# in %#", self.txtSearch , [autoSuggestModel label]] ;
}else{
cell.lblText.text = [autoSuggestModel label];
}
return cell;
}
I could make bold particular string with below code. but i want to append both string.
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc] initWithString:self.txtSearch];
NSRange boldRange = [[autoSuggestModel label] rangeOfString:self.txtSearch];
[boldString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:boldRange];
[cell.lblText setAttributedText: boldString];
update you method like bellow
if ([[autoSuggestModel type] isEqualToString:#"product"] || [[autoSuggestModel type] isEqualToString:#"category"]){
cell.textLabel.attributedText = [self getBoldText:cell withSearch:#"search text" withAutoSuggestModel:#"autoSuggestModel"];
}else{
cell.lblText.text = [autoSuggestModel label];
}
//check above code by the following method
-(NSMutableAttributedString*)getBoldText:(UITableViewCell*)cell withSearch:(NSString*)searchText withAutoSuggestModel:(NSString*)autoSuggestModelText{
NSString *title = [NSString stringWithFormat:#"%# in %#", searchText,autoSuggestModelText];
cell.textLabel.text = title;
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont boldSystemFontOfSize:16];
NSDictionary *attrs = #{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:cell.textLabel.attributedText];
[attrStr addAttributes:attrs range:[title rangeOfString:autoSuggestModelText]];
return attrStr;
}
A very cursory look at the NSString documentation has a section called "combining strings" and a method called stringByAppendingString:
Using this method, it should be incredibly straight-forward to accomplish what you're trying to do.
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc]
initWithString:[self.txtSearch stringByAppendingString:yourMutableString]];
I have a created a custom cell in iOS.In custom cell there are many labels.For few labels the data of first & fourth custom cell is always same.There are total 5 records in my data source array.Now there are these issues i face.
Why cell for row at index is called only two times when there are 4 records in array.
Data of first & 4th row is always same.
Please tell me how can i resolve this issue.
CODE:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cell for row called %d",(int)[arr_post count]);
//define variables here
NSMutableAttributedString *mutableAttributeStr;
NSAttributedString *attributeStr;
static NSString *CellIdentifier = #"homeCell";
float x_pos;
HomeCell *cell = [self.table_view
dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//get the post data
Post *user_post=[arr_post objectAtIndex:indexPath.row];
cell.tv_post.text=user_post.post_description;
cell.tv_post.font = [UIFont fontWithName:user_post.font_family size:[user_post.font_size floatValue]];
cell.label_name.text=user_post.post_title;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [formatter dateFromString:user_post.modification_date];
if([user_post.post_image isEqualToString:#"none"] && [user_post.post_video isEqualToString:#"none"])
{
x_pos=cell.tv_post.frame.origin.x;
cell.tv_post_leading_space.constant=-(x_pos);
[cell.img_post setHidden:true];
}
//set the like count
NSString *first_like_user=user_post.recent_like_name;
int count=(int)[first_like_user length];
float like_count=[user_post.like_count intValue];
//chek if tehre are any likes on the post
NSLog(#"recent like name is %#",user_post.recent_like_name);
NSLog(#"like count is %f",like_count);
if(like_count>0)
{
NSLog(#"inside like count block");
NSString *str_like_count=[NSString stringWithFormat:#"%lu",(unsigned long)like_count-1];
if(like_count==1)
{
if([myUsername isEqualToString:first_like_user])
{
first_like_user=#"You like this post";
count=3;
}
else
{
first_like_user=[first_like_user stringByAppendingString:#" like this post"];
}
}
else if(like_count==2)
{
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" other like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
else
{
if(like_count>1000)
{
like_count=like_count/1000;
str_like_count=[NSString stringWithFormat:#"%lu",(unsigned long)like_count];
str_like_count=[str_like_count stringByAppendingString:#"k"];
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" others like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
else
{
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" others like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
}
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
//set the like label dynamic height & width
cell.label_like_count.attributedText = mutableAttributeStr;
CGSize maximumLabelSize = CGSizeMake(187,9999);
CGSize requiredSize = [cell.label_like_count sizeThatFits:maximumLabelSize];
CGRect labelFrame = cell.label_like_count.frame;
labelFrame.size.height = requiredSize.height;
cell.label_like_count.frame = labelFrame;
// cell.label_like_count.lineBreakMode = NSLineBreakByWordWrapping;
cell.label_like_count.numberOfLines = 0;
[cell.label_like_count sizeToFit];
[cell.label_like_count setAttributedText:mutableAttributeStr];
}
//show dynamic comment
NSMutableArray *user_comments=user_post.comments;
float comment_count=[user_post.comment_count intValue];
NSLog(#"arr comments count is %lu",(unsigned long)comment_count);
if(comment_count>0)
{
NSLog(#"post id is %#",user_post.id);
NSMutableAttributedString *mutableAttributeStr;
NSAttributedString *attributeStr;
for(l=0;l<[user_comments count];l++)
{
NSLog(#"inside loop %d",l);
Comment *comment=[user_comments objectAtIndex:l];
if(l==0)
{
NSLog(#"l is zero");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
NSLog(#"comment string is %#",comment_string);
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.first_comment setAttributedText:mutableAttributeStr];
}
else if(l==1)
{
NSLog(#"l is 1");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
NSLog(#"comment string is %#",comment_string);
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.second_cmment setAttributedText:mutableAttributeStr];
}
else if(l==2)
{
NSLog(#"l is 2");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.third_comment setAttributedText:mutableAttributeStr];
}
}
}
else
{
NSLog(#"not inside loop");
}
cell.label_time.text=[BaseController getTimestampForDate:date];
return cell;
}
EDIT:
I have read somewhere that for performance reasons UITable resume the cell.Because i feel i get this issue when there are more than 3 rows.
EDIT:
I have found a strange situation here if i try don't use the condition if(like_count>0) & simply set the text fo label with out this condition then it works fine for me.
Thanks in advance.
Cell are reused, so you have to cover all case in your execution path.
As you already found, if(like_count>0) and if(comment_count>0) imply that if there is no count, the text label is not changed and the old value will stay there.
You have to add } else { cell.label_like_count.attributedText = nil } kind of code to cover all cases. Alternatively, you can add some cleanup code in - (void)prepareForReuse in the cell class (don't forget [super prepareForReuse]).
in HomeCell override prepareForReuse:. In that method, set the .text (or .attributedText) property to nil on all of your labels. Then see what happens.
Cells are reused and the table always creates only the cells that are currently visible. When you show the screen, three cells will be visible. When you scroll and one cell becomes hidden and another one appears, it's actually the same cell instance.
The usual way to handle this behavior is to subclass UITableViewCell and do all that setup there. The reset to a default state can be added to -prepareForReuse method, e.g.
- (void)prepareForReuse {
[super prepareForReuse];
self.first_comment.text = nil;
self.second_comment.text = nil;
self.third_comment.text = nil;
}
To fix your code without having a specific cell subclass, let's first simplify by removing the repetitive patterns from your code:
for (NSUInteger i = 0; i < [user_comments count]; i++) { //i is the traditional variable name for iterating
Comment *comment = user_comments[i]; //updating to newer syntax
// start of the repetitive pattern
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
NSMutableAttributedString* mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
NSAttributedString attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
// end of the repetitive pattern
if (i == 0) {
[cell.first_comment setAttributedText:mutableAttributeStr];
}
else if (i == 1) {
[cell.second_comment setAttributedText:mutableAttributeStr];
}
else if (i == 2) {
[cell.third_comment setAttributedText:mutableAttributeStr];
}
}
Now you can combine it with resetting the value:
NSArray *commentLabels = #[cell.first_comment, cell.second_comment, cell.third_comment];
for (NSUInteger i = 0; i < 3; i++) {
UILabel *label = commentLabels[i];
// reset if there is no comment
if (i >= [user_comments count]) {
label.text = nil;
continue;
}
Comment *comment = user_comments[i];
NSString *comment_string = [NSString stringWithFormat:#"%# %#", comment.user_name, comment.comment];
int count = (int)[comment.user_name length];
NSMutableAttributedString* mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
NSAttributedString attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica-Bold" size:14.0 range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
label.attributedText = mutableAttributeStr;
}
Check the number of elements in the table and be sure the number is correct in the delegate numberOfRowsInSection:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return the_correct_items_number;
}
If the count is correct, try with a local array (just for test). Note: if you update the source array using network requests, consider to use the dispatch_async calling to update you content.
Use methods prepareForReuse in your custom cell .
// if the cell is reusable (has a reuse identifier), this is called just before the cell is returned from the table view method dequeueReusableCellWithIdentifier:. If you override, you MUST call super.
- (void) prepareForReuse {
// set empty or nil of your repeated element .
[super prepareForReuse];
}
hope it help you .
try replacing
if (cell==nil)
{
cell = [[HomeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
with
//if (cell==nil)
//{
cell = [[HomeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// }
After you dequeue cell, write the below line:-
[cell.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
I have a simple blog app that lists the articles on the main screen as a UITableView. Everything looks fine when first loading, but when I scroll down and back up, it redraws the cells wrong, and...well, just check out this picture.
The code I use for the cells is listed below. What am I doing incorrect?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSString *substring = #"http://316apps.com/ipreachersblog/wp";
NSRange textRange = [entry.articleImage rangeOfString:substring];
NSString *substring2 = #"http://ipreacher.files.wordpress.com";
NSRange textRange2 = [entry.articleImage rangeOfString:substring2];
if(textRange.location != NSNotFound){
NSString *thearticleImage = entry.articleImage;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"src=\"([^\"]+)\"" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *someString = thearticleImage;
NSString *oneurl = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSString *finalstring = [oneurl stringByReplacingOccurrencesOfString:#"src=\"" withString:#""];
NSString *thefinalstring = [finalstring stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"Copperplate-Bold" size:21];
UIFont *cellFont2 = [UIFont fontWithName:#"Copperplate-Bold" size:18];
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:30];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.numberOfLines = 3;
cell.detailTextLabel.text = articleDateString;
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
[cell.imageView setImageWithURL:[NSURL URLWithString:thefinalstring] placeholderImage:[UIImage imageNamed:#"Icon-60#2x.png"]];
UIColor *bobcatred = UIColorFromRGB(0x841617);
cell.textLabel.textColor = bobcatred;
cell.backgroundColor = [UIColor lightGrayColor];
}
else if (textRange2.location != NSNotFound){
NSString *thearticleImage = entry.articleImage;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"src=\"([^\"]+)\"" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *someString = thearticleImage;
NSString *oneurl = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSString *finalstring = [oneurl stringByReplacingOccurrencesOfString:#"src=\"" withString:#""];
NSString *thefinalstring = [finalstring stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"Copperplate-Bold" size:21];
UIFont *cellFont2 = [UIFont fontWithName:#"Copperplate-Bold" size:18];
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:30];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.numberOfLines = 3;
cell.detailTextLabel.text = articleDateString;
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
[cell.imageView setImageWithURL:[NSURL URLWithString:thefinalstring] placeholderImage:[UIImage imageNamed:#"Icon-60#2x.png"]];
UIColor *bobcatred = UIColorFromRGB(0x841617);
cell.textLabel.textColor = bobcatred;
cell.backgroundColor = [UIColor lightGrayColor];
}
else {
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:30];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"Copperplate-Bold" size:21];
UIFont *cellFont2 = [UIFont fontWithName:#"Copperplate-Bold" size:18];
cell.imageView.image = [UIImage imageNamed:#"Icon-60#2x.png"];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = articleDateString;
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
UIColor *bobcatred = UIColorFromRGB(0x841617);
cell.textLabel.textColor = bobcatred;
cell.textLabel.numberOfLines = 3;
cell.backgroundColor = [UIColor lightGrayColor];
}
return cell;
}
The cell is custom, its implementation is:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)layoutSubviews {
[super layoutSubviews];
self.imageView.frame = CGRectMake(1,6,60,60);
float limgW = self.imageView.image.size.width;
if(limgW > 0) {
self.textLabel.frame = CGRectMake(74,self.textLabel.frame.origin.y,self.textLabel.frame.size.width,self.textLabel.frame.size.height);
self.detailTextLabel.frame = CGRectMake(74,self.detailTextLabel.frame.origin.y,self.detailTextLabel.frame.size.width,self.detailTextLabel.frame.size.height);
}
}
#end
I want to make sl.asl bold in the below and colour it based on it's numeric value in the below. Any ideas?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateStyle:NSDateFormatterShortStyle];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
ServiceLevel *sl = (ServiceLevel *)[self.importedRows objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%# - %#", sl.name , sl.asl];
return cell;
}
An NSAttributedString ought to do the trick.
Like:
NSString *name = #"SampleName";
NSUInteger asl = 2;
NSString *t_string = [NSString stringWithFormat:#"%# - %d", name , asl];
NSUInteger t_nameLength = name.length;
NSUInteger t_aslLength = 1;
UIColor *t_color = nil;
switch (asl) {
case 1:
t_color = [UIColor redColor];
break;
case 2:
t_color = [UIColor greenColor];
break;
default:
t_color = [UIColor blackColor];
break;
}
NSMutableAttributedString *t_attributedString = [[NSMutableAttributedString alloc] initWithString:t_string];
[t_attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Arial" size:14.0] range:NSMakeRange(0, t_nameLength)];
[t_attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, t_nameLength)];
[t_attributedString addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Arial-BoldMT" size:14.0] range:NSMakeRange(t_nameLength + 3, t_aslLength)];
[t_attributedString addAttribute:NSForegroundColorAttributeName value:t_color range:NSMakeRange(t_nameLength + 3, t_aslLength)];
cell.textLabel.attributedText = t_attributedString;
Create an NSAttributedString and assign it to cell.textLabel.attributedText. For example:
NSDictionary *attributes = #{
NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:[UIFont fontWithName:#"Helvetica-Bold" size:16]
};
NSString *delimiter = #" - ";
NSString *text = [NSString stringWithFormat:#"%#%#%#", sl.name, delimiter, sl.asl];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
[attributedText addAttributes:attributes range:NSMakeRange(sl.name.length + delimiter.length, sl.asl.length)];
cell.textLabel.attributedText = attributedText;
UPDATED CODE - for bolding a part of a text and changing the colour based on a numeric value
Please d some initial research before you post questions on stackoverflow, and show us what you've tried in the past so that we can help you accordingly.
You can set a part of your text to bold by using the NSAttributedString:
//To bold a part of a string you have to let it know where you want the bold to start and end from, for that you need to know the length of your sl.asl variable
NSMutableAttributedString * attributedAsl = [[NSMutableAttributedString alloc] initWithAttributedString:sl.asl];
NSString *delimiter = #" - "; //This is what will be written to separate sl.name and sl.asl
NSString *begginingString = [NSString stringWithFormat:#"%#%#", delimiter, sl.name];
//What we dont want bolded
NSInteger startBoldFromEndOfBeginningString = [begginingString length];
//The length of text we want bolded - your sl.asl variable
NSInteger slAslLength = ((NSString)sl.asl).length;
UIFont *font= [UIFont fontWithName:#"Helvetica-Bold" size:25.0f];
[attributedAsl addAttribute:NSFontAttributeName value:font range:NSMakeRange(startBoldFromEndOfBeginningString, slAslLength)];
cell.textLabel.attributedText = attributedAsl;
And then you can set the text color like so
cell.textLabel.textColor = [UIColor redColor];
Now if you want to change the textColor based on the numeric value of something you then have to start playing with RGB values which make up color values.
[UIColor colorWithRed:1.0 green:0.0 blue:1.0 alpha:1.0];
What will be helpful to ensure an even distribution of colors to the desired range of colours would be to know the highest the number can go to.
Lets say you are displaying the alphabet of the english language in a tableView, the total number of cells would be 26, and you want to change the color of text for each cell displayed, one solution would be to do this:
CGFloat maxNumber = 26; //total number of letters
CGFloat dynamicColor = 1.0/maxNumber * indexPath.row;
[UIColor colorWithRed:dynamicColor green:0.0 blue:1.0 alpha:1.0];
this will ensure that each textColor is different for each cell that is displayed.