我有一个 NSString,我想知道它的高度来创建一个合适的 UILabel。
这样做
NSString *string = @"this is an example";
CGSize size = [string sizeWithFont:[UIFont systemFontOfSize:10.0f]
forWidth:353.0
lineBreakMode:UILineBreakModeWordWrap];
float height = size.height;
高度现在是 13.0。 如果我使用这个字符串
NSString *string = @"this is an example this is an example this is an example
this is an example this is an example this is an example
this is an example this is an example this is an example
this is an example this is an example this is an example
this is an example this is an example this is an example
this is an example ";
高度始终为 13.0(宽度为 353,这是不可能的)...我做错了什么?
添加:
size.width;
工作正常...所以如果 lineBreakMode 不正确...但它是正确的,不是吗?
最佳答案
你正在做的事情没有像你期望的那样工作的原因是因为
– sizeWithFont:forWidth:lineBreakMode:
用于“计算单行文本的指标”,而
-sizeWithFont:constrainedToSize:lineBreakMode:
用于“计算多行文本的指标”。来自documentation :
Computing Metrics for a Single Line of Text
– sizeWithFont: – sizeWithFont:forWidth:lineBreakMode: – sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:
Computing Metrics for Multiple Lines of Text
– sizeWithFont:constrainedToSize: – sizeWithFont:constrainedToSize:lineBreakMode:
尝试使用 -sizeWithFont:constrainedToSize:lineBreakMode:
代替,例如这是我通常做的:
CGSize maximumLabelSize = CGSizeMake(353,9999);
CGSize expectedLabelSize = [string sizeWithFont:label.font
constrainedToSize:maximumLabelSize
lineBreakMode:label.lineBreakMode];
CGRect newFrame = label.frame;
newFrame.size.height = expectedLabelSize.height;
label.frame = newFrame;
关于ios - 获取 NSString 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6962641/