ios - 获取 NSString 高度

标签 ios iphone nsstring uilabel sizewithfont

我有一个 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/

相关文章:

ios - 在某些设备上的 iPhone safari 中网页加载缓慢

ios - 将字符串添加到 uibutton 标题

c++ - NSString* 到 char*?

iphone - buildDate 和 buildNumber 的 plist 属性名称?

ios - MVVM 和 iOS 用例

android - ZeroBrane DebugServer 连接被拒绝

ios - 在 Swift 中合并两个滚动和缩放的图像

ios - 如何从 iPhone 中的项目 test-Info.plist 中检索标签中的 Bundle Version?

iphone - 检查 C 枚举是否存在

ios - 排序 ABMultiValueRef(kABPersonPhoneProperty)