UILabel文字大小自适应之--SizeToFit

UILabel文字大小自适应之--SizeToFit


在做UIlabel的时候一直苦于没有好的方法来实时控制label的宽度,后来发现iOS自带一个sizeToFit的方法可以根据label里的文字来自动适应尺寸

看下效果图

附上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
@interface ViewController ()
 
@property (strong,  nonatomic ) UITextField *textField;
@property (strong,  nonatomic ) UILabel *label;
 
@end
 
@implementation ViewController
 
- ( void )viewDidLoad {
     [ super viewDidLoad];
 
     //按钮
     UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(60, 50, 200, 40)];
     btn.backgroundColor = [UIColor grayColor];
     [btn setTitle: @"使用SizeToFit" forState:UIControlStateNormal];
     [btn addTarget: self action: @selector (btnEvent) forControlEvents:UIControlEventTouchUpInside];
     [ self .view addSubview:btn];
 
     //textField
     _textField = [[UITextField alloc] initWithFrame:CGRectMake(60, 100, 200, 30)];
     [[ NSNotificationCenter defaultCenter] addObserver: self selector: @selector (changeTextField) name:UITextFieldTextDidChangeNotification object: nil ];
     _textField.backgroundColor = [UIColor purpleColor];
     [ self .view addSubview:_textField];
 
     //label
     _label = [[UILabel alloc] initWithFrame:CGRectMake(60, 150, 40, 20)];
     _label.backgroundColor = [UIColor orangeColor];
     [ self .view addSubview:_label];
}
 
- ( void )btnEvent
{
     [_label sizeToFit];
}
 
- ( void )changeTextField
{
     _label.text = _textField.text;
}
 
@end

你可能感兴趣的:(IOS,开发,UI)