How do I write a custom init for a UIView subclass in Swift?

前端 未结 5 1835
野的像风
野的像风 2021-01-29 20:48

Say I want to init a UIView subclass with a String and an Int.

How would I do this in Swift if I\'m just subclassing

5条回答
  •  有刺的猬
    2021-01-29 20:51

    I create a common init for the designated and required. For convenience inits I delegate to init(frame:) with frame of zero.

    Having zero frame is not a problem because typically the view is inside a ViewController's view; your custom view will get a good, safe chance to layout its subviews when its superview calls layoutSubviews() or updateConstraints(). These two functions are called by the system recursively throughout the view hierarchy. You can use either updateContstraints() or layoutSubviews(). updateContstraints() is called first, then layoutSubviews(). In updateConstraints() make sure to call super last. In layoutSubviews(), call super first.

    Here's what I do:

    @IBDesignable
    class MyView: UIView {
    
          convenience init(args: Whatever) {
              self.init(frame: CGRect.zero)
              //assign custom vars
          }
    
          override init(frame: CGRect) {
               super.init(frame: frame)
               commonInit()
          }
    
          required init?(coder aDecoder: NSCoder) {
               super.init(coder: aDecoder)
               commonInit()
          }
    
          override func prepareForInterfaceBuilder() {
               super.prepareForInterfaceBuilder()
               commonInit()
          }
    
          private func commonInit() {
               //custom initialization
          }
    
          override func updateConstraints() {
               //set subview constraints here
               super.updateConstraints()
          }
    
          override func layoutSubviews() {
               super.layoutSubviews()
               //manually set subview frames here
          }
    
    }
    

提交回复
热议问题