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

来源:互联网 发布:淘宝推广pid 编辑:程序博客网 时间:2024/04/29 23:30

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:boundslimitedToNumberOfLines:numberOfLines];

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

    return textRect;

}

// 重新绘制text的位置

-(void)drawTextInRect:(CGRect)requestedRect {

    CGRect actualRect = [selftextRectForBounds:requestedRectlimitedToNumberOfLines:self.numberOfLines];

    [superdrawTextInRect:actualRect];

}

@end


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

@interface UILabel (LeftTopAlign)


- (void) textLeftTopAlign;


@end


@implementation UILabel (LeftTopAlign)


- (void) textLeftTopAlign

{

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStylealloc]init];

    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 的滚动效果



0 0
原创粉丝点击