問題描述
是否可以將標籤內的文本與“大”框架垂直對齊 (Is it possible to vertically align text inside labels with a "large" frame)
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 to contain the content.
However on iPad the screen is larger and I want the text to appear at the top left point of the label, not in the middle as it do when you use numberOfLines
property. I know you can horizontally align the text, but it must be possible to align the text to the top left also? Or is it impossible.
Screenshot:
‑‑‑‑‑
參考解法
方法 1:
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.
方法 2:
I actually noticed that using
[Blue setSizeToFit]
does align vertically to the top. The default being centered.
方法 3:
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
方法 4:
You can do it as follows
Set your label's
numberOfLines
property 0 from IBSet your label's
lineBreakMode
asUILineBreakModeWordWrap
(very very important)
now whatever you set on the label just append few @"\n" to it..... ex.‑
[yourTextLabel setText:@"myLabel\n\n\n\n\n"];
方法 5:
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)];
}
(by LuckyLuke、EmptyStack、nembleton、Hons、Fahim Parkar、AppsolutEinfach)