码迷,mamicode.com
首页 > 其他好文 > 详细

UILabel自适配text文本的宽度

时间:2015-08-20 06:57:39      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

#import "ViewController.h"


@interface ViewController ()


@property (nonatomic, strong) UILabel *fontLabel;

@property (nonatomic, strong) UITextField *textField;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    _textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 320, 40)];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTextField) name:UITextFieldTextDidChangeNotification object:nil];

    _textField.backgroundColor = [UIColor purpleColor];

    _textField.keyboardType = UIKeyboardTypeEmailAddress;

    _textField.returnKeyType = UIReturnKeyDone;

    _textField.delegate = self;

    [self.view addSubview:_textField];

    

    

    _fontLabel = [[UILabel alloc]initWithFrame:CGRectMake(10,140,320,40)];

    _fontLabel.backgroundColor = [UIColor blueColor];

    NSString *fontString = @"明月几时有,把酒问酒吧";

    CGSize labelSize = CGSizeMake(320,2000);

    CGSize fontStringSize = [fontString boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} context:nil].size;

    

    _fontLabel.frame = CGRectMake(10, 260, fontStringSize.width, 40);

    _fontLabel.text = fontString;

//    [_fontLabel sizeToFit];

    _fontLabel.textAlignment = NSTextAlignmentRight;

    [self.view addSubview:_fontLabel];

    

    UIButton *click = [[UIButton alloc]initWithFrame:CGRectMake(50, 100, 140, 40)];

    [click setTitle:@"点击我吧" forState:UIControlStateNormal];

    click.backgroundColor = [UIColor redColor];

    [click addTarget:self action:@selector(touchMe) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:click];

    

    

}



- (void)touchMe {

    [_fontLabel sizeToFit];

}


- (void)changeTextField {

     _fontLabel.text = self.textField.text;

//    [_fontLabel sizeToFit];

}


UILabel自适配text文本的宽度

标签:

原文地址:http://my.oschina.net/u/585206/blog/494854

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!