繁体   English   中英

在 UILabel 上设置插图

[英]Set insets on UILabel

我正在尝试在 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
    }

}

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

恕我直言,您还必须更新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
    }

}

请更新您的代码如下

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

此代码与接受的答案不同,因为接受的答案使用 insetBy(inset) 而此答案使用 inset(by: inset)。 当我在 iOS 10.1 和 Swift 4.2.1 自动完成中添加这个答案时,没有给你 rect.inset(by:),我不得不手动输入它。也许它在 Swift 5 中可以,我不确定

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM