@interface ViewController ()
@property (nonatomic, strong) UITextField *textFile;
@property (nonatomic, strong) UILabel *label;
@end
- (void)viewDidLoad{
//1.获得主屏幕的宽和高
CGFloat screeW = [UIScreen mainScreen].bounds.size.width;
CGFloat screeH = [UIScreen mainScreen].bounds.size.height;
//textFile
//比例布局
UITextField *textFile = [[UITextField alloc] initWithFrame:CGRectMake(screeW * 0.125, screeH * 0.15, screeW * 0.75, screeH * 0.055)];
//设置文本输入框的边框模式
textFile.borderStyle = UITextBorderStyleBezel;
//通过通知实时监测textFile里面的值
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTextFile) name:UITextFieldTextDidChangeNotification object:nil];
self.textFile = textFile;
//设置文体大小
textFile.font = [UIFont systemFontOfSize:20];
//设置字体颜色
textFile.textColor = [UIColor blackColor];
[self.view addSubview:textFile];
//label
//比例布局
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(screeW * 0.125, screeH * 0.25, 100, 50)];
//label背景颜色
label.backgroundColor = [UIColor lightGrayColor];
//字体颜色
label.textColor = [UIColor whiteColor];
//字体大小
label.font = [UIFont systemFontOfSize:20];
//_label.numberOfLines = 0;一旦加了这句话,文本的自适应回事宽度不变,高度变,否则就是高度不变,宽度变
self.label = label;
[self.view addSubview:label];
//按钮
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(screeW * 0.125, screeH * 0.35, screeW * 0.75, screeH * 0.055)];
// 添加按钮标题
[button setTitle:@"自适应文本" forState:UIControlStateNormal];
//文字颜色
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//按钮背景颜色
button.backgroundColor = [UIColor brownColor];
//添加按钮点击事件
[button addTarget:self action:@selector(btnEvent) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)changeTextFile{
self.label.text = self.textFile.text;
}
- (void)btnEvent{
[self.label sizeToFit];
}