您的位置:首页 > 产品设计 > UI/UE

3种方法实现UILabel的左上角对齐显示文字

2016-08-19 15:01 393 查看
1、继承UILabel 改变origin的值重新绘制

@interface TopLeftLabel :
UILabel

@end

#import
"TopLeftLabel.h"

@implementation TopLeftLabel

- (id)initWithFrame:(CGRect)frame {

    return [super
initWithFrame:frame];

}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{

   
CGRect textRect = [super
textRectForBounds:bounds
limitedToNumberOfLines:numberOfLines];

    textRect.origin.y = bounds.origin.y;

    return textRect;

}

// 重新绘制text的位置

-(void)drawTextInRect:(CGRect)requestedRect {

   
CGRect actualRect = [self
textRectForBounds:requestedRect
limitedToNumberOfLines:self.numberOfLines];

    [super
drawTextInRect:actualRect];

}

@end

2、第二种方法 写一个UILabel的分类 

@interface UILabel (LeftTopAlign)

- (void) textLeftTopAlign;

@end

@implementation UILabel (LeftTopAlign)

- (void) textLeftTopAlign

{

   
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle
alloc]init];

    paragraphStyle.lineBreakMode =
NSLineBreakByWordWrapping;

    

   
NSDictionary *attributes =
@{NSFontAttributeName:[UIFont
systemFontOfSize:17],
NSParagraphStyleAttributeName:paragraphStyle.copy};

    

   
CGSize labelSize = [self.text
boundingRectWithSize:CGSizeMake(207,
999)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;

    

   
CGRect dateFrame =CGRectMake(2,
140,
CGRectGetWidth(self.frame)-5,
labelSize.height);

    self.frame = dateFrame;

}

@end

3、直接用UITextView代替 UILabel 然后禁用UITextView 的滚动效果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息