Nick
Nick

Reputation: 492

Class not overriding storyboard

In main.storyboard I have a UIView, and in the identity inspector I set the class of the view to my custom UIView class called "customView." All this does is set the background color to purple. However, the color does not change when I run the app, it stays the color it originally is. What am I doing wrong?

class CustomView: UIView {


override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.purple
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}
} 

Upvotes: 0

Views: 173

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100503

The right way to create a custom UIView is to have a shared function that you call from both init(frame:) and init?(coder:) which will make a guarantee that it'll behave the same whether it's setted as a class in IB or instantiated in code

class CustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        sharedLayout()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        sharedLayout()
    }
    func sharedLayout() {
        // all the layout code from above
    }

}

Upvotes: 1

Williamberg Farias
Williamberg Farias

Reputation: 105

As the view you are using is loaded from storyboard the method override init(frame: CGRect) is not called. You must set the background color on required init?(coder aDecoder: NSCoder) method.

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.backgroundColor = UIColor.purple
}

Upvotes: 3

Related Questions