带有属性文本的 UILabel textInsets

问题描述

我有以下子类,并希望添加功能以轻松更改行高、字符间距等。这需要使用 NSAttributedString 类来完成,但是每当我使用段落样式设置标签属性文本时,文本标签周围的插图在顶部和底部被忽略。此实现在没有段落样式或“文本”属性的情况下也能工作...

class Label: UILabel {

    override var text: String? {
        get {
            return super.attributedText?.string
        }
        set {
            self.updateText(newValue)
        }
    }
    
    public var textInsets: UIEdgeInsets = .zero {
        didSet {
            self.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)
        return textRect.inset(by: textInsets.invert())
    }
    
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: textInsets))
    }

    private func updateText(_ text: String?) {
        // Setting attributed text here...
    }
    
}

我在具有自动高度的 UIStackView 中有标签。我可以看到标签周围有填充,但文本没有居中......每当我使用段落样式时。我需要行高倍数的段落样式。

任何帮助将不胜感激!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)