lunes, 15 de enero de 2018

iOS: Custom view with xib

1) Create a .xib file

The Root view will be linked to the contentView of the class file

2) Create a swift class:

import UIKit

class CustomView: UIView {

    @IBOutlet var contentView: UIView!
    ...
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        commonInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    
    private func commonInit() {
        
        Bundle.main.loadNibNamed(String(describing: type(of:self)), owner: self, options: nil)
        addSubview(contentView)
        contentView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        contentView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        
        updateLayout()
    }
    
    override func layoutSubviews() {
        updateLayout()
    }
    
    private func updateLayout() {
        contentView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
    }
}