ios - function to set UILabel text from float not correctly updating when setting self (only works with super) -


i've got function on subclass of uilabel:

func settextfromfloat(amount: float) {     super.text = formatcurrency(fromfloat: amount) } 

and another:

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

and override init:

override internal var text: string? {     didset {         super.text = formatcurrency(fromstring: self.text)     } } 

i can call:

mylabel.settextfromfloat(2.5) 

and works.

it wasn't working though, because first tried set self.text in settextfromfloat() method instead of super.text. why did have change set super? why didn't self work?

this looks interview question ;-)

the problem overriding var text stored variable , adding observer (via didset) rewrites every time same value in infinite loop (if calling self in line instead of super)

it works super because relying on implementation do not have observer set data in place.

a quick solution remove observer, either way, calling settextfromfloat(amount: float) gets job done.

a quick snippet solving 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()         // additional setup after loading view, typically nib.         lab.settextfromfloat(2.5)     } } 

either way, may want think @ possible extension, , refactor code such.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -