在UILabel上设置插图

时间:2018-06-26 09:32:26

标签: ios swift uiedgeinsets

我正在尝试在UILabel中设置一些插图。它工作得很好,但是现在 UIEdgeInsetsInsetRectCGRect.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
    }

}

任何人都知道如何将插图设置为UILabel吗?

5 个答案:

答案 0 :(得分:9)

请如下更新您的代码

 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))
    }
}

答案 1 :(得分:6)

Imho,您还必须更新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
    }

}

答案 2 :(得分:0)

答案 3 :(得分:0)

对于iOS 10.1Swift 4.2.1,请使用rect.inset(by:

此:

override func draw(_ rect: CGRect) {

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

    super.drawText(in: rect.inset(by: inset))
}

答案 4 :(得分:0)

Swift 5 用 draw(...) 替换方法 drawText(...)

extension UILabel {

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