在UILabel上设置insets

Jac*_*erg 7 ios uiedgeinsets swift

我正试图在UILabel中设置一些插件.它工作得很好,但现在 UIEdgeInsetsInsetRect已被替换,CGRect.inset(by:)我无法找到如何解决这个问题.

当我试图使用CGRect.inset(by:)我的插图,然后我收到UIEdgeInsets不可转换的消息CGRect.

我的代码

class TagLabel: UILabel {

    override func draw(_ rect: CGRect) {
        let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)

        super.drawText(in: CGRect.insetBy(inset))
//        super.drawText(in: UIEdgeInsetsInsetRect(rect, inset)) // Old code
    }

}
Run Code Online (Sandbox Code Playgroud)

任何人都知道如何设置UILabel的插图?

Rak*_*tel 13

请更新您的代码,如下所示

 class TagLabel: UILabel {

    override func draw(_ rect: CGRect) {
        let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)
        super.drawText(in: rect.insetBy(inset))
    }
}
Run Code Online (Sandbox Code Playgroud)


And*_*tta 9

恕我直言,您还必须更新intrinsicContentSize

class InsetLabel: UILabel {

    let inset = UIEdgeInsets(top: -2, left: 2, bottom: -2, right: 2)

    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: inset))
    }

    override var intrinsicContentSize: CGSize {
        var intrinsicContentSize = super.intrinsicContentSize
        intrinsicContentSize.width += inset.left + inset.right
        intrinsicContentSize.height += inset.top + inset.bottom
        return intrinsicContentSize
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 这是更好的答案。如果您非常挑剔,以至于弄乱了插图,那么您也会需要 sizeToFit()。上面的intrinsicContentSize方法可以让它正常工作。 (3认同)