ios - 无法在 tableViewcell 中设置 UILabel 填充

标签 ios iphone swift uitableview uilabel

我已经使用 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)

效果是这样的

enter image description here

你看,第一个标签在重新加载单元格后得到它的填充。

请建议如何使用上述扩展来实现 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/

相关文章:

ios - clang : error: linker command failed with exit code 1 (use -v to see invocation) in Xcode 10. 0 和 Ionic 3

iphone - 使用 CocosDenshion 在指定位置启动声音?

iphone - 将原点设置为屏幕中心而不是屏幕左上角?(iPhone)

swift - 在 swift 3 中使用基本身份验证获取请求

swift - Mac OS AVPlayer Xcode 10.2.1 swift 5.0.1 无法运行

ios - 选择节标题时显示行

ios - 如何使从横向到纵向的模糊图像适合纵横比?

ios - 声明 __block 变量的正确方法是什么?

iphone - setAnimationRepeatAutoreverses 的行为不符合我的预期

以编程方式快速访问闭包成员