我已经使用 StackOverflow 的 popular thread 设置了我的 UILabel 填充用于解决自动布局问题。 这个线程基本上是一个 UILabel 扩展。
部分答案是:
class NRLabel : UILabel {
var textInsets = UIEdgeInsets.zero {
didSet { invalidateIntrinsicContentSize() }
}
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
let invertedInsets = UIEdgeInsets(top: -textInsets.top,
left: -textInsets.left,
bottom: -textInsets.bottom,
right: -textInsets.right)
return UIEdgeInsetsInsetRect(textRect, invertedInsets)
}
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets))
}
}
一切正常,添加了填充,但我需要重新加载 tableViewcell 才能看到效果。
我已经覆盖了我的 customCell 的 viewWillLayoutSubviews() 函数,用于填充
self.chatLabel.textInsets = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
效果是这样的
你看,第一个标签在重新加载单元格后得到它的填充。
请建议如何使用上述扩展来实现 UILabel 填充,以便解决此问题。
最佳答案
将这两个函数添加到您的扩展中并删除所有其他函数:
override func drawText(in rect: CGRect) {
let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
override var intrinsicContentSize : CGSize {
var intrinsicSuperViewContentSize = super.intrinsicContentSize
intrinsicSuperViewContentSize.height += topInset + bottomInset
intrinsicSuperViewContentSize.width += leftInset + rightInset
return intrinsicSuperViewContentSize
}
关于ios - 无法在 tableViewcell 中设置 UILabel 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44388935/