文本自适应(sizeToFit)

来源:互联网 发布:我的世界手机版火车js 编辑:程序博客网 时间:2024/04/28 04:55

@interface ViewController ()

@property (nonatomic,strong) UITextField *textFile;

@property (nonatomic,strong) UILabel *label;

@end

- (void)viewDidLoad{   

//1.获得主屏幕的宽和高

    CGFloat screeW = [UIScreenmainScreen].bounds.size.width;

    CGFloat screeH = [UIScreenmainScreen].bounds.size.height;

    //textFile

    //比例布局

     UITextField *textFile = [[UITextFieldalloc] initWithFrame:CGRectMake(screeW *0.125, screeH * 0.15, screeW *0.75, screeH * 0.055)];

   //设置文本输入框的边框模式

    textFile.borderStyle =UITextBorderStyleBezel;

   //通过通知实时监测textFile里面的值

    [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(changeTextFile)name:UITextFieldTextDidChangeNotificationobject:nil];

    self.textFile = textFile;

    //设置文体大小

    textFile.font = [UIFontsystemFontOfSize:20];

    //设置字体颜色

    textFile.textColor = [UIColorblackColor];

    [self.viewaddSubview:textFile];

    //label

   //比例布局

    UILabel *label = [[UILabelalloc] initWithFrame:CGRectMake(screeW *0.125, screeH * 0.25,100, 50)];

   //label背景颜色

    label.backgroundColor = [UIColorlightGrayColor];

   //字体颜色

    label.textColor = [UIColorwhiteColor];

    //字体大小

    label.font = [UIFontsystemFontOfSize:20];

 //_label.numberOfLines = 0;一旦加了这句话,文本的自适应回事宽度不变,高度变,否则就是高度不变,宽度变

    self.label = label;

    [self.viewaddSubview:label];

    

    //按钮

    UIButton *button = [[UIButtonalloc] initWithFrame:CGRectMake(screeW *0.125, screeH * 0.35, screeW * 0.75, screeH *0.055)];

    // 添加按钮标题

    [button setTitle:@"自适应文本"forState:UIControlStateNormal];

    //文字颜色

    [button setTitleColor:[UIColorwhiteColor] forState:UIControlStateNormal];

    //按钮背景颜色

    button.backgroundColor = [UIColorbrownColor];

    //添加按钮点击事件

    [button addTarget:selfaction:@selector(btnEvent)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:button];

}


- (void)changeTextFile{

    self.label.text =self.textFile.text;

}

- (void)btnEvent{


    [self.labelsizeToFit];

}


0 0
原创粉丝点击