mardi 12 avril 2016

Custom UIView for an UIViewController in Swift

I use code to create the view (with subviews) for UIViewController's this is how I do it:

  1. override loadView()

    class MYViewController: UIViewController {
    
    var myView: MyView! { return self.view as MyView }
    
       override func loadView() {
          view = MyView() 
       }
    }
    
    

and here is how I create my custom view:

class MyView: UIView {

    // MARK: Initialization

    override init (frame : CGRect) {
        super.init(frame : frame)
        addSubviews()
        setupLayout()
    }

    convenience init () {
        self.init(frame:CGRect.zero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("This class does not support NSCoding")
    }

    // MARK: Build View hierarchy

    func addSubviews(){
        // add subviews
    }

    func setupLayout(){
        // Autolayout
    }

    // lazy load views
}

I do this for all my View Controllers and I am looking for more elegant way, because this process is repetitive, so is there any solution for make that generic for example, create a super abstract class, or create an extension for UIViewController and UIView, Protocols ? I am new for swift and I think that Swift can have a better elegant solution with it's modern patterns

Aucun commentaire:

Enregistrer un commentaire