Label或Button自適應寬度或文字大小

1、確定Label或Button的字體大小,使其寬度自適應

UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 120, 30)];
contentLabel.font = [UIFont systemFontOfSize:15];//——–>定義Font的大小
contentLabel.backgroundColor = [UIColor redColor];
contentLabel.text = @”我已知曉,且已閱讀並同意以上條款”;
[contentLabel sizeToFit];//——–>注意和上面一句代碼順序不能顛倒
[self.View addSubview:contentLabel];

2、確定Label或Button的寬度,使字體大小自適應

//無需自己設置字體大小
UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 120, 30)];
contentLabel.backgroundColor = [UIColor redColor];
contentLabel.text = @”我已知曉,且已閱讀並同意以上條款”;
contentLabel.adjustsFontSizeToFitWidth = YES;//默認爲NO——–>注意和上面一句代碼順序不能顛倒
[self.View addSubview:contentLabel];
如果是Button的話,和上面一樣,只有一點小小的區別:

[button.titleLabel sizeToFit];
button.titleLabel.adjustsFontSizeToFitWidth = YES;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章