我正在尝试根据不同的字符串长度计算 UILabel 的高度。
func calculateContentHeight() -> CGFloat{ var maxLabelSize: CGSize = CGSizeMake(frame.size.width - 48, CGFloat(9999)) var contentNSString = contentText as NSString var expectedLabelSize = contentNSString.boundingRectWithSize(maxLabelSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(16.0)], context: nil) print("\(expectedLabelSize)") return expectedLabelSize.size.height }
以上是我用来确定高度的当前函数,但它不起作用。我将非常感谢我能得到的任何帮助。我更喜欢 Swift 而不是 Objective C 中的答案。
使用扩展String
String
extension String { func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(boundingBox.height) } func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(boundingBox.width) } }
还有 on NSAttributedString(有时非常有用)
NSAttributedString
extension NSAttributedString { func height(withConstrainedWidth width: CGFloat) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) return ceil(boundingBox.height) } func width(withConstrainedHeight height: CGFloat) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil) return ceil(boundingBox.width) } }
只需更改方法attributes中的值extension String
attributes
extension String
从
[NSFontAttributeName: font]
至
[.font : font]