找出基于Swift中的String的UILabel的大小
我正在尝试根据不同的string长度来计算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 }
以上是我用来确定高度的当前function,但它不工作。 我将不胜感激任何帮助,我可以得到。 我会在Swift中而不是客观的C.
在String
上使用扩展名
Swift 3
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(withConstraintedHeight 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) } }
也在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) } }
斯威夫特4
只需在extension String
方法中更改attributes
的值即可
从
[NSFontAttributeName: font]
至
[.font : font]
对于多行文本,此答案无法正常工作。 您可以使用UILabel构build不同的string扩展
extension String { func height(constraintedWidth width: CGFloat, font: UIFont) -> CGFloat { let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude)) label.numberOfLines = 0 label.text = self label.font = font label.sizeToFit() return label.frame.height } }
UILabel得到一个固定的宽度,并将.numberOfLines设置为0.通过添加文本并调用.sizeToFit(),它会自动调整到正确的高度。
代码是用Swift 3 written编写的