覆盖UILabel文本获取器不起作用

时间:2018-08-22 21:39:30

标签: swift uikit uilabel uistoryboard

我正在使用情节提要,我希望有一些标签始终在标签的开头显示给定的表情符号。

我有以下代码:

import UIKit
import CocoaLumberjack

class PITLabel: UILabel {

    override public var text: String? {
        set {
            super.text = newValue?.prependedWithGenderEmoji()
            DDLogDebug(" set super.text: \(super.text ?? "")")
        }

        get {
            let newVal = super.text?.prependedWithGenderEmoji()
            DDLogDebug(" get super.text: \(newVal ?? "")")
            return newVal
        }
    }

    override public var attributedText: NSAttributedString? {
        set {
            super.attributedText = newValue
            DDLogDebug(" set super.attributed: \(super.attributedText ?? NSAttributedString(string: ""))")
        }

        get {
            let genderString = super.attributedText?.string.prependedWithGenderEmoji()
            let rangePointer = UnsafeMutablePointer<NSRange>.allocate(capacity: 8)
            rangePointer.pointee = NSMakeRange(0, 1)
            let originalAttributes = super.attributedText?.attributes(at: 0, effectiveRange: rangePointer)

            let newAttributedString = NSAttributedString(string: genderString!, attributes: originalAttributes)

            DDLogDebug(" get super.attributed: \(newAttributedString)")
            return newAttributedString
        }
    }

}

并且我已在情节提要中将标签设置为类PITLabel

enter image description here

enter image description here

运行该应用程序时,控制台输出中将显示以下内容:

 get super.text: ‍♂️ PiT SETTINGS
 get super.attributed: ‍♂️ PiT SETTINGS{
NSColor = "UIExtendedSRGBColorSpace 0.0352941 0.498039 0.662745 1";
    <snip>
}

这是预期的。

但是在应用的用户界面中,它不会显示表情符号。

enter image description here

我想念什么?

1 个答案:

答案 0 :(得分:1)

因为您实际上没有在文本之前添加它。应该是:

override public var text: String? {
    set {
        let result = newValue.prependedWithGenderEmoji()
        super.text = result
    }

    get {
        return super.text
    }
}

在Interface Builder中设置文本不会调用您要覆盖的text setter。您必须在代码中进行设置。

yourPitLabel.text = "PiT SETTING