0

So I overrode the init(frame) to do a bunch of stuff:

class InputField: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame);
        let label = UILabel(frame: CGRect(x: 8, y: 8, width: 73, height: 30));
        label.text = "I want";
        label.font = UIFont(name: "Avenir-Book", size: 26.0);
        addSubview(label);
        NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leadingMargin, multiplier: 1.0, constant: 8.0).isActive = true;

    }

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

}

The problem is that the second init() is called not the first one. The way I have it set up in storyboard is by having a plain empty UIView whose class is InputField. Why does it use the second one and not the first one?

I don't want to create the InputField programmatically as I'd much rather see the Views I'm setting up in the storyboard. I know how to if I'm stuck, but I mostly wanna learn how to do it this way.

edit: as stated in comment, the current workaround is doing that configuration code in init(coder). But this still doesn't answer: Why is that being called and not init(frame)?

JoeVictor
  • 1,806
  • 1
  • 17
  • 38
  • Any configuration code, such as what you have in your init frame override, may be placed in a separate method and called from any or all initializers. – Fred Faust Feb 19 '17 at 01:49
  • Yeah I realized that. I set it up so that the code is called in init(decoder). But then why does init(frame) exist though? – JoeVictor Feb 19 '17 at 01:51
  • here's a thorough answer for that question: http://stackoverflow.com/questions/8373176/how-is-view-initialized-when-loaded-via-a-storyboard – Fred Faust Feb 19 '17 at 01:55
  • That's exactly what i needed, thanks! – JoeVictor Feb 19 '17 at 02:18

1 Answers1

1

There are different convenience methods to help initialize a view. When a view is actually initialized only one of the many methods(-frame, -coder, etc) are going to be invoked.
If you need to perform any custom initialization, you can have a common init method.

Community
  • 1
  • 1
ystack
  • 1,785
  • 12
  • 23