Reputation: 383
I have a UILabel in my app and text in that UILabel is fetching from internet so text length will differ so i want to add background color to black for UILabel but i also want the width of the UILabel to change when there is small length text will fetch in it. here is my code.
cell.songtitl.text = [[rssData objectAtIndex:indexPath.row]title];
this is how i am setting text to uilabel inside cellForRowAtIndexPath. and here is my TableViewCell.h
@property (weak, nonatomic) IBOutlet UILabel *songtitl;
here is what i want to avoid by setting background color on short titles.
Upvotes: 0
Views: 234
Reputation: 580
I'm using these codes all of my project. These are giving you height and width dynamically. Hope it helps
+ (CGFloat) calculateHeightForText:(NSString *)str forWidth:(CGFloat)width forFont:(UIFont *)font {
CGFloat result = 20.0f;
if (str) {
CGSize textSize = { width, 20000.0f };
CGSize size = [str sizeWithFont:font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
result = MAX(size.height, 20.0f);
}
return result;
}
+ (CGFloat) calculateWidthForText:(NSString *)str forHeight:(CGFloat)height forFont:(UIFont *)font {
CGFloat result = 20.0f;
if (str) {
CGSize textSize = { 20000.0f, height };
CGSize size = [str sizeWithFont:font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
result = MAX(size.width, 20.0f);
}
return result;
}
Upvotes: 0
Reputation: 3329
Use this code for set UILable
width as per text length
NSString *text = @"this is fortesting" ;
UIFont *font = [UIFont systemFontOfSize:10];
CGSize size = [(text ? text : @"") sizeWithFont:font constrainedToSize:CGSizeMake(220, 9999) lineBreakMode:NSLineBreakByWordWrapping];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(46, 200, size.width, size.height)];
label.numberOfLines = 0;
label.textColor = [UIColor grayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.text = (text ? text : @"");
label.font = font;
label.backgroundColor = [UIColor redColor];
[self.view addSubview:label];
I hope this code useful for you.
Upvotes: 1