0

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)
}
} 
Nick Griffith
  • 492
  • 1
  • 6
  • 15
  • 1
    If I understand your problem correctly, you might want to have a look at [How do I create a custom iOS view class and instantiate multiple copies of it (in IB)?](https://stackoverflow.com/questions/9251202/how-do-i-create-a-custom-ios-view-class-and-instantiate-multiple-copies-of-it-i) – MadProgrammer May 15 '18 at 00:39
  • 1
    Interface builder `decodes` a view (because the views are precompiled into archives). It doesn't `init with frame`.. So why do you have the color in the `init(frame: CGRect)`? – Brandon May 15 '18 at 00:42
  • Yeah, whoooopppps, I just moved it out of there and it works – Nick Griffith May 15 '18 at 00:42
  • 1
    It's a good idea to put your setup code in a separate method and call it from both inits. – vacawama May 15 '18 at 00:43

2 Answers2

3

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
}
  • 1
    This is the correct answer. Storyboards invoke `init?(coder:)`, not `init(frame:)`. As @vacawama suggests in their comment, you should put your setup code in a common method and then call it from both `init(frame:)` and `init?(coder:)` – Duncan C May 15 '18 at 01:07
  • I got in the habit of setting up everything programmatically and so I got used to putting everything in the init(frame: CGRect) method. Thank you for helping me! – Nick Griffith May 15 '18 at 01:14
1

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
    }

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87