ScareCrow ScareCrow - 1 year ago 141
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

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
. 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
as well. Now I got this:

override 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 Source

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

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

    convenience init () {

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

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

let u = MyView(frame:
let v = MyView()

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download