Tar*_*era 4 objective-c nsstring ios
我正在使用 NSString 的 sizeWithAttributes 方法来获取 NSString 的动态高度。
我的字符串是 @“这是地址行 1 \n 这是地址行 2”
但该方法仅返回 line1 的大小(在 \n 字符之前)
有没有办法在字符串大小中包含 \n ?
您不能用于sizeWithAttributes计算多行文本的大小。想一想。多行文本的大小取决于必须绘制的宽度。sizeWithAttributes不允许您指定分配的宽度。
你需要使用boundingRectWithSize:options:attributes:context:. 指定具有所需宽度和非常大高度的尺寸。返回的值将为您提供将文本换行在指定大小内所需的大小。
其使用的一个例子是:
NSString *addressString = ... // your string to measure
NSDictionary *attributes = @{ NSFontAttributeName : [UIFont fontWithName:kFontName size:kProductFont] };
CGFloat desiredWidth = 300; // adjust accordingly
CGRect neededRect = [addressString
boundingRectWithSize:CGSizeMake(desiredWidth, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes context:nil];
CGFloat neededHeight = neededRect.size.height;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1291 次 |
| 最近记录: |