1

I've created a custom button class as follows.

import UIKit

class LogButtonView: UIButton {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.frame = CGRectMake(200, 200, 100, 100)

        self.layer.cornerRadius = 50
        self.layer.borderWidth = 1
        self.layer.borderColor = self.tintColor.CGColor
    }

}

And I know how to use it in story board.

But how can I create an instance of it dynamically in ViewController.swift and add it to containerView?

import UIKit

class ViewController: UIViewController {
    @IBOutlet var containerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let logBtn = LogButtonView() // Missing argument for parameter 'coder' in call
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

And if possible, I want all LogButtonView instances to be of the same size, so I set self.frame = CGRectMake(200, 200, 100, 100). But the instances in story board seem to be of the size I dragged them to be.

0

1 Answer 1

5

To create views in code, dont't use init(coder:), use init(frame:) instead. And don't forget to add it in view hierarchy after creating

class LogButtonView: UIButton {
    init() {
        super.init(frame: CGRectMake(200, 200, 100, 100))
        //other stuff
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//viewDidLoad:
override func viewDidLoad() {
    super.viewDidLoad()
    let logBtn = LogButtonView()
    self.view.addSubview(logBtn)
}

but I don't think you want to set frame in init of view, because it means that every LogButtonView will be in the same position. Much better approach would be:

class LogButtonView: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        //other stuff
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//viewDidLoad:
override func viewDidLoad() {
    super.viewDidLoad()
    let logBtn = LogButtonView(frame: CGRectMake(200, 200, 100, 100))
    self.view.addSubview(logBtn)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.