iOS-UILabel插入为零不起作用

iOS-UILabel插入为零不起作用,ios,Ios,我之所以遵循本教程,是因为我想删除内部标签中的填充 代码似乎非常有用,但我不想让它工作: import UIKit @IBDesignable class EdgeInsetLabel: UILabel { var textInsets = UIEdgeInsets.zero { didSet { invalidateIntrinsicContentSize() } } override func textRect(forBounds bounds: C

我之所以遵循本教程,是因为我想删除内部标签中的填充

代码似乎非常有用,但我不想让它工作:

import UIKit

@IBDesignable
class EdgeInsetLabel: UILabel {
    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }
    override func textRect(forBounds bounds: CGRect, 
        limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = bounds.inset(by: 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 textRect.inset(by: invertedInsets)
    }
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: textInsets))
    }
}

extension EdgeInsetLabel {
    @IBInspectable
    var leftTextInset: CGFloat {
        set { textInsets.left = newValue }
        get { return textInsets.left }
    }

    @IBInspectable
    var rightTextInset: CGFloat {
        set { textInsets.right = newValue }
        get { return textInsets.right }
    }

    @IBInspectable
    var topTextInset: CGFloat {
        set { textInsets.top = newValue }
        get { return textInsets.top }
    }

    @IBInspectable
    var bottomTextInset: CGFloat {
        set { textInsets.bottom = newValue }
        get { return textInsets.bottom }
    }
}
结果是:


我缺少什么?使用
myLabel.sizeToFit()
删除标签周围的任何可移动空间。

您缺少了
textRect(forBounds:)
子类中的重写
textRect部分:

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

插图基于单个字符的字体--而非:

因此,使用
UILabel
中的默认系统字体,添加一些其他字符:


如果要将背景剪裁到单个字符的边界框中,则需要使用
Text Kit
函数。这里有一个很好的开始:

我添加了,但没有改变。没有改变