【问题标题】:Get text height depending on width根据宽度获取文本高度
【发布时间】:2014-02-16 21:53:42
【问题描述】:

我有一个包含任意数量字符的 NSString。 现在想把这个字符串画成一个矩形。 例如,矩形需要 250 像素宽。

我想知道如何获取此文本的高度 具有特定的字体和大小。

【问题讨论】:

  • 请看NSStringUIStringDrawing分类中的方法。

标签: ios objective-c text width uitextview


【解决方案1】:

来自 NSString UIKit Additions (https://developer.apple.com/library/ios/documentation/uikit/reference/NSString_UIKit_Additions/DeprecationAppendix/AppendixADeprecatedAPI.html#//apple_ref/occ/instm/NSString/sizeWithFont:constrainedToSize:)

使用 sizeWithFont:constrainedToSize:lineBreakMode:

以一种在您的情况下使用宽度为 250 且高度非常高(假设为 10000)的约束的方式使用它。 然后它返回实际宽度(可能略小于 250)和所需的高度。

但请注意,它最近已被弃用。您可以使用 boundingRectWithSize:options:attributes:context: 从 iOS 7 开始。通常不推荐使用的方法会存在一段时间,但您不能依赖它。因此,如果您希望您的应用程序在 iOS 6 或更早版本中运行,那么您可能会使用已弃用的方法一段时间,或者您可以检查操作系统并使用旧方法或新方法继续前进。

抱歉,如果您使用的是 OS-X 而不是 iOS。在那种情况下,我的回答根本没有帮助。您没有标记操作系统。

【讨论】:

【解决方案2】:

您可以使用 'sizeWithFont:' 方法获取高度和宽度,如下所示:

UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];

// Get the width of a string ...
CGSize size = [@"Some string here!" sizeWithFont:myFont];

CGSize 是一个 C 结构体,因此可以通过如下方式访问高度和宽度:

  // Print height and width
  NSLog(@"h: %f \t w:%f", size.height, size.width);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 2010-10-28
相关资源
最近更新 更多