Search code examples
iosswiftuikituistoryboardiboutlet

How do you call an IBOutlet element's initializer?


I wrote the following subclass of UITextField:


    var imageView: UIButton? = nil

    var options: [String]? = nil

    let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 30)

    override init(frame: CGRect) {
        super.init(frame:frame)
        self.backgroundColor = Constants.darkPurple
        self.textColor = .white
        self.layer.cornerRadius = 10
        self.clipsToBounds = true
        self.translatesAutoresizingMaskIntoConstraints = false
        self.tintColor = .clear

        Constants.styleDropDownField(self)
    }



    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //fatalError("init(coder:) has not been implemented")
    }
}

When I add instances of this class programmatically, it works fine. But when I add an instance of the class in the storyboard and then connect it with an IBAction, it's just a blank white text field without any of the properties I assigned in the class's initializer - it seems that the initializer isn't being called at all. Is there any way to call the element's initializer? Or is there another function, similar to viewDidLoad, that will run when the text field is loaded?


Solution

  • You'll have to call the implementation given in init(frame:) in init(coder:) because this method is called when used from the storyboard. Here is the code:

    override init(frame: CGRect) {
        super.init(frame:frame)
        initialSetup()
    }
    
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialSetup()
    }
    
    func initialSetup() {
        self.backgroundColor = Constants.darkPurple
        self.textColor = .white
        self.layer.cornerRadius = 10
        self.clipsToBounds = true
        self.translatesAutoresizingMaskIntoConstraints = false
        self.tintColor = .clear
    
        Constants.styleDropDownField(self)
    }