In my application I have multiple tableviews with custom cells. Some of the text in the cells are spread out on between 2-4 lines so the height of the label is large enough
sizeToFit
does not work in UITableCellView
, because the Cells are reused during scrolling.
The solution is to calculate the table cell height according to the font and font size and adjust the label height to it.
As it was quite difficult to find the solution on the web I wrote a short post about it
I actually noticed that using
[Blue setSizeToFit]
does align vertically to the top. The default being centered.
Its impossible to align the text in UILabel vertically. But, you can dynamically change the height of the label using sizeWithFont: method of NSString, and just set its x and y as you want.
As an alternative you can use UITextField. It supports the contentVerticalAlignment peoperty as it is a subclass of UIControl. You have to set its userInteractionEnabled to NO to prevent user from typing text on it.
I added in viewDidLoad
self.textLabel.numberOfLines = 0;
[self.textLabel sizeToFit];
make sure your constraints are set correct, so that the label is allowed to shrink or grow. Otherwise it won't work.
Here is the Same Question asked by SomeOne. you'll find more appropriate way to solve this problem.they guys did great explanation over it.
I think so, you should take a look of this.
here in that thread many answers suggest set the dynamic frame for the UILabel on the basis of text
as below snippet of code described.
CGSize theStringSize = [textToBeUsed sizeWithFont:lblTitle.font constrainedToSize:labelSize lineBreakMode:lblTitle.lineBreakMode];
lblTitle.frame = CGRectMake(lblTitle.frame.origin.x, lblTitle.frame.origin.y, theStringSize.width, theStringSize.height);
lblTitle.text = theText;
// lblTitle is the Label used for showing the Text.
you can get more precise idea rather than using textField
here it is
In iOS 7 sizeWithFont:
is now deprecated!
Several solutions like subclassing UILabel
have to be adapted.
My solution for top aligned label text:
In a subclass TopVerticalAlignmentLabel : UILabel
override drawRect:
as follows:
- (void)drawRect:(CGRect)rect
{
CGRect labelStringRect = [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, CGFLOAT_MAX)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{ NSFontAttributeName: self.font, /* further attributes */}
context:nil];
[super drawTextInRect:CGRectMake(0, 0, self.frame.size.width, labelStringRect.size.height)];
}