简体   繁体   English

设置属性在init迅速扩展?

[英]set property at init with an extension in swift?

How can we use extension to set a default value ? 如何使用extension设置默认值? For example, if I create an UILabel in my storyboard , i set text value to "toto" in the storyboard . 例如,如果我创建UILabel在我的storyboard ,我的文本值设置为在“TOTO” storyboard Now I want to create an extension to set my text value to "popo" when the label will be init in the app. 现在,我想创建一个扩展程序,以在标签将在应用程序中初始化时将我的文本值设置为“ popo”。 To be more clear, I want to do that to set a default value in the whole app to my UILabel. 更清楚地说,我想这样做是在整个应用程序中为我的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. 请不要告诉我在情节提要中设置ma值,因为这不是我所需要的。

Can a "default" value for the text property be provided for labels created in a Storyboard? 可以为故事板中创建的标签提供text属性的“默认”值吗? 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): 话虽如此,您可以做的是重写awakeFromNib (在从Storyboard / Nib文件加载视图之后调用):

extension UILabel {

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

}

Don't Create extension 不创建extension

You should create subclass of UILabel assign it to your needed place in storyboard 您应该创建UILabel子类,将其分配到情节提要中所需的位置。

import UIKit

class MyLabel: UILabel {


override func awakeFromNib() {
    super.awakeFromNib()

    self.text = "POPO"
}
}

You can use this class in storyboard this way 您可以通过这种方式在情节提要中使用此类

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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