我在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
工作?
答案 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)
}
}
无论哪种方式,您可能希望将此视为可能的扩展,并重构代码。