iOS 11 已经修复了这个问题,此问题仅针对 iOS 10 及其低于 iOS 10 的版本!
iOS 10 中,当设置tableViewCell
的样式为.subtitle
时,即使设置detailTextLabel?.numberOfLines = 0
,也会出现多行文字溢出的问题,如图:
解决方法:
在tableViewCell
中重写
systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority)
来修复此问题:
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
if #available(iOS 11, *) {
return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
}
else {
layoutIfNeeded()
var size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
guard let textLabel = textLabel,
let detailTextLabel = detailTextLabel
else { return size }
let detailHeight = detailTextLabel.frame.height
if detailTextLabel.frame.minX > textLabel.frame.minX {
let textHeight = textLabel.frame.height
if detailHeight > textHeight {
size.height += detailHeight - textHeight
}
}
else {
size.height += detailHeight
}
return size
}
}