简体   繁体   中英

set property at init with an extension in swift?

How can we use extension to set a default value ? For example, if I create an UILabel in my storyboard , i set text value to "toto" in the storyboard . Now I want to create an extension to set my text value to "popo" when the label will be init in the app. To be more clear, I want to do that to set a default value in the whole app to my UILabel. Hope this is clear.

extension UILabel {
   open override func ??? { 
       self.text == "popo"
   }
}

Please, don't tell me to set ma value in the storyboard cause this not what i need.

Can a "default" value for the text property be provided for labels created in a Storyboard? Yes.

Is it a good idea? Probably not...

Having said that, what you could do is override awakeFromNib (which is called after the view is loaded from a Storyboard/Nib file):

extension UILabel {

    open override func awakeFromNib() {
        super.awakeFromNib()
        self.text = "popo"
    }

}

Don't Create extension

You should create subclass of UILabel assign it to your needed place in storyboard

import UIKit

class MyLabel: UILabel {


override func awakeFromNib() {
    super.awakeFromNib()

    self.text = "POPO"
}
}

You can use this class in storyboard this way

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM