JAA*_*JAA 11 iphone nsstring uilabel sizewithfont ios
我有一个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不正确一样......但它是,不是吗?
Pen*_*One 21
你正在做的事情并不像你期望的那样有效
– sizeWithFont:forWidth:lineBreakMode: 
用于"计算单行文本的度量",而
-sizeWithFont:constrainedToSize:lineBreakMode:
用于"计算多行文本的度量标准".从文档:
计算单行文本的度量标准
Run Code Online (Sandbox Code Playgroud)– sizeWithFont: – sizeWithFont:forWidth:lineBreakMode: – sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:计算多行文本的度量标准
Run Code Online (Sandbox Code Playgroud)– 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;