文本自适应(sizeToFit)

@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];

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值