Anish 웃 Anish 웃 - 1 year ago 189
iOS Question

How to create custom view programmatically in swift having controls text field, button etc

I am trying to access the

from another class using the following code in ViewController.swift ..

var view = MyCustomView(frame: CGRectZero)

.. in the
method. The problem is the view does not get initialized in the simulator.

I have already set class in storyboard for the current ViewController.

class MyCustomView: UIView {
var label: UILabel = UILabel()
var myNames = ["dipen","laxu","anis","aakash","santosh","raaa","ggdds","house"]

override init(){

override init(frame: CGRect) {
super.init(frame: frame)

required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")

func addCustomView() {
label.frame = CGRectMake(50, 10, 200, 100)
label.textAlignment = NSTextAlignment.Center
label.text = "test label"

var btn: UIButton = UIButton()
btn.frame=CGRectMake(50, 120, 200, 100)
btn.setTitle("button", forState: UIControlState.Normal)
btn.addTarget(self, action: "changeLabel", forControlEvents: UIControlEvents.TouchUpInside)

var txtField : UITextField = UITextField()
txtField.frame = CGRectMake(50, 250, 100,50)
txtField.backgroundColor = UIColor.grayColor()

Answer Source

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(top: 0, left: 0, width: 200, height: 50)

Note that you also most certainly need the addSubview otherwise your view is not added to the view hierarchy.

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