我做到了,你想要什麼用實施分類:
.H
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end
.M
@implementation UILabel (VerticalAlign)
#pragma mark
#pragma mark - Align Methods
- (void)alignTop
{
[self setFrame:[self newLabelFrame:UIControlContentVerticalAlignmentTop]];
}
- (void)alignBottom
{
[self setFrame:[self newLabelFrame:UIControlContentVerticalAlignmentBottom]];
}
#pragma mark
#pragma mark - Helper Methods
- (CGRect)newLabelFrame:(UIControlContentVerticalAlignment)alignment
{
CGRect labelRect = self.frame;
NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading;
CGRect textRect = [self.text boundingRectWithSize:CGSizeMake(227.f, CGFLOAT_MAX)
options:options
attributes:@{NSFontAttributeName:self.font}
context:nil];
CGFloat textOffset = labelRect.size.height - textRect.size.height;
UIEdgeInsets contentInsets;
if (alignment == UIControlContentVerticalAlignmentTop)
{
if (textOffset < (labelRect.size.height/2.f))
{
contentInsets = UIEdgeInsetsMake(-textOffset, 0.f, 0.f, 0.f);
}
else
{
contentInsets = UIEdgeInsetsMake(0.f, 0.f, textOffset, 0.f);
}
}
else
{
if (textOffset < (labelRect.size.height/2.f))
{
contentInsets = UIEdgeInsetsMake(0.f, 0.f, -textOffset, 0.f);
}
else
{
contentInsets = UIEdgeInsetsMake(textOffset, 0.f, 0.f, 0.f);
}
}
return UIEdgeInsetsInsetRect(labelRect, contentInsets);
}
@end
請記住,您需要將「NumberOfLines」設置爲0.本示例適用於多行選項!
後您實現上述類別,你可以簡單地做:
[myLabel setText:finalRecipe];
[myLabel alignTop];
乾杯!
可能的重複[如何設置UILable for iOS應用程序的左上對齊?](http://stackoverflow.com/questions/7192088/how-to-set-top-left-alignment-for-uilable- for-ios-application) –
您是否嘗試過使用UIFont更改字體大小? – prince
爲什麼你沒有檢查標記任何給定的答案! –