设置self时设置UILabel文本浮动不正确更新的功能(仅适用于super)

时间:2016-01-27 16:21:50

标签: ios swift super

我在UILabel的子类上有这样的函数:

func setTextFromFloat(amount: Float) {
    super.text = formatCurrency(fromFloat: amount)
}

另一个:

internal func formatCurrency(fromFloat amount: Float) -> String {
    let currencyFormatter: NSNumberFormatter = NSNumberFormatter()
    currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    currencyFormatter.locale = NSLocale.currentLocale()
    print(currencyFormatter.stringFromNumber(NSNumber(float: amount))!)
    return currencyFormatter.stringFromNumber(NSNumber(float: amount))!
}

覆盖init:

override internal var text: String? {
    didSet {
        super.text = formatCurrency(fromString: self.text)
    }
}

然后我可以打电话:

myLabel.setTextFromFloat(2.5)

它有效。

它最初没有工作,因为我首先尝试在self.text方法而不是setTextFromFloat()中设置super.text。为什么我必须将其更改为设置super?为什么没有self工作?

1 个答案:

答案 0 :(得分:2)

  

这看起来像是一个面试问题; - )

问题基本上是你要覆盖var text存储变量并添加一个观察者( via didSet ),它基本上每次在无限循环中重写相同的值(如果您在该行中调用 self 而非 super

适用于super因为您依赖让该观察者设置数据的实现。

快速解决方案是删除该观察者,无论哪种方式,您正在调用setTextFromFloat(amount: Float)来完成工作。

  

解决问题的快速摘录

class ExtendedLabel : UILabel {
    func setTextFromFloat(amount: Float) {
        self.text = formatCurrency(fromFloat: amount)
    }
    internal func formatCurrency(fromFloat amount: Float) -> String {
        let currencyFormatter: NSNumberFormatter = NSNumberFormatter()
        currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
        currencyFormatter.locale = NSLocale.currentLocale()
        let formattedFloat = currencyFormatter.stringFromNumber(NSNumber(float: amount))!
        print(formattedFloat)
        return formattedFloat
    }
}

class ViewController: UIViewController {
    @IBOutlet var lab : ExtendedLabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        lab.setTextFromFloat(2.5)
    }
}

无论哪种方式,您可能希望将此视为可能的扩展,并重构代码。