ScareCrow ScareCrow - 1 month ago 12
Swift Question

Swift subclass UIView

I've just started using Swift. I've read the book and I learn better while doing so I started something simple.

I want to subclass

UIView
and show a login like view. I've created this in Objective-C but now I want to port it to Swift. I do not use storyboards, so I create all my UI in code.

But the first problem is that I must implement
initWithCoder
. I gave it a default implementation since It won't be called. Now when I run the program it crashes because I've to implement
initWithFrame
as well. Now I got this:

override init() {
super.init()
println("Default init")
}

override init(frame: CGRect) {
super.init(frame: frame)
println("Frame init")
}

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
println("Coder init")
}


My question is where should I create my textfield etc... and if I never implement frame and coder how can I "hide" this?

Answer

I usually do something like this, its a bit verbose.

class MyView: UIView {
    override init (frame : CGRect) {
        super.init(frame : frame)
        addBehavior()
    }

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

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

    func addBehavior (){
        print("Add all the behavior here")
    }
}



let u = MyView(frame: CGRect.zero)
let v = MyView()

(Edit: I've edited my answer so that the relation between the initializers is more clear)