iOS 下,UILable自适应高度的方法
2015-11-09 11:32
316 查看
主要思路是通过调用
注意这里不能调用
1.针对非AutoLayout的情况,直接调整frame:
2.针对AutoLayout的情况,需要更新约束:
UILabel的
- (CGSize)sizeThatFits:(CGSize)size方法来得到label的自适应高度值。
注意这里不能调用
NSString的
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode方法来获得高度,因为如果未来label的可以配置其他行间距,自定义字体等等,那么此方法便会失效。 其实,iOS的UILabel已经可以支持不同的字体属性,比如大小,颜色。所以此方法已经不再是正确的了
1.针对非AutoLayout的情况,直接调整frame:
- (void)autoHeightOfLabel:(UILabel *)label{ //Calculate the expected size based on the font and linebreak mode of your label // FLT_MAX here simply means no constraint in height CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX); CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize]; //adjust the label the the new height. CGRect newFrame = label.frame; newFrame.size.height = expectedLabelSize.height; label.frame = newFrame; [label updateConstraintsIfNeeded]; }
2.针对AutoLayout的情况,需要更新约束:
- (void)autoHeightOfLabel:(UILabel *)label{ //Calculate the expected size based on the font and linebreak mode of your label // FLT_MAX here simply means no constraint in height CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX); //add the new height constraint to the label for (NSLayoutConstraint *constraint in label.constraints) { if (constraint.firstItem == label && constraint.firstAttribute == NSLayoutAttributeHeight && constraint.secondItem == nil) { constraint.constant = expectedLabelSize.height; break; } } }
相关文章推荐
- 基本的UI控件和布局文件
- MultipartRequest上传文件
- AndroidUI设计——Gridview
- 面试题.自己的总结UI部分(一)
- Builder - 创建者模式
- deque 双向队列
- 根据UILabel里面字体的个数来计算UILabel的宽度
- easyui内嵌iframe问题解决
- Rogue游戏(四)——药品、楼梯、升级
- 加载自定义xib UIView的方法和加载纯代码 UIView代码的区别
- UI界面-帧布局
- faad warning: Bitstream value not allowed by specification
- UI界面-相对布局
- easyui 处理多行的操作基础
- request doesn't contain a multipart/form-data or multipart/mixed stream
- Exception in thread "main" java.lang.NullPointerException at java.lang.ProcessBuilder.start(
- iOS UIcollectionView 和 UITableView 限制item 或cell的交换方法
- easyui datagrid 让某行复选框置灰不能选
- 使用UIActivityViewController展现自定义分享选项
- UITableView使用,建立二级功能栏