I did what you need by implementing the category:
.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
Remember that you need to set "NumberOfLines" to 0. This example works with multi-line parameters!
After implementing the above category, you can simply do:
[myLabel setText:finalRecipe]; [myLabel alignTop];
Hurrah!
Tom Calmon Aug 23 '14 at 2:49 a.m. 2014-08-23 14:49
source share