gpt4 book ai didi

ios - 设置 self 时无法正确更新 float 的 UILabel 文本的函数(仅适用于 super)

转载 作者:搜寻专家 更新时间:2023-11-01 07:27:27 24 4
gpt4 key购买 nike

我在 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))!
}

还有一个覆盖初始化:

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

然后我可以调用:

myLabel.setTextFromFloat(2.5)

而且有效。

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

最佳答案

This looks as an interview question ;-)

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

它适用于 super,因为您依赖于不要让观察者将数据设置到位的实现。

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

A quick snippet solving the problem follows:

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

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

关于ios - 设置 self 时无法正确更新 float 的 UILabel 文本的函数(仅适用于 super),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com