这是我使用的扩展.您不必传递有关字体或行高的任何信息,因为属性字符串已知道其值.
extension NSAttributedString { func height(containerWidth: CGFloat) -> CGFloat { let rect = self.boundingRect(with: CGSize.init(width: containerWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) return ceil(rect.size.height) } func width(containerHeight: CGFloat) -> CGFloat { let rect = self.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: containerHeight), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) return ceil(rect.size.width) } }
像这样使用:
let height = detailPetViewModel!.description.height(containerWidth: Sizes.screenWidth - 40 + 10)