3種方法實現UILabel的左上角對齊顯示文字
1、繼承UILabel 改變origin的值重新繪製
@interface TopLeftLabel : UILabel
@end
#import "TopLeftLabel.h"
@implementation TopLeftLabel
- (id)initWithFrame:(CGRect)frame {
return [superinitWithFrame:frame];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
CGRect textRect = [supertextRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
textRect.origin.y = bounds.origin.y;
return textRect;
}
// 重新繪製text的位置
-(void)drawTextInRect:(CGRect)requestedRect {
CGRect actualRect = [selftextRectForBounds:requestedRect
limitedToNumberOfLines:self
[superdrawTextInRect:actualRect];
}
@end
2、第二種方法 寫一個UILabel的分類
@interface UILabel (LeftTopAlign)
- (void) textLeftTopAlign;
@end
@implementation UILabel (LeftTopAlign)
- (void) textLeftTopAlign
{
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName:[UIFontsystemFontOfSize:17], NSParagraphStyleAttributeName:paragraphStyle.copy};
CGSize labelSize = [self.textboundingRectWithSize:CGSizeMake(207, 999) options:NSStringDrawingUsesLineFragmentOriginattributes:attributes context:nil].size;
CGRect dateFrame =CGRectMake(2, 140, CGRectGetWidth(self.frame)-5, labelSize.height);
self.frame = dateFrame;
}
@end
3、直接用UITextView代替 UILabel 然後禁用UITextView 的滾動效果