Programmatically creating UIButton,UILabel,UITextField Using Swift

UIButton

UIButton is the simplest UI component in iOS was the first component which I learnt in objective C. Here is the code that created the UIButton dynamically in swift – apple’s new programming language. You can also customize the button and play with it.

UIBUTTON-SWIFT-PROGRAMMATICALLY

1
2
3
4
5
6
let dunamicButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
dunamicButton.backgroundColor = UIColor.greenColor()
dunamicButton.setTitle("Button", forState: UIControlState.Normal)
dunamicButton.frame = CGRectMake(100, 100, 100, 50)
dunamicButton.addTarget(self, action: "buttonTouched:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(dunamicButton)

 

And call the targeted method like below :

1
2
3
4
func buttonTouched(sender:UIButton!)
{
println("It Works!!!")
}

UILabel

UILabel class is simply a read only text field that can be used to draw a single or multiple lines of static text.

UILABEL-SWIFT-PROGRAMMATICALLY

Here is the code for creating the UILabel dynamically using Swift.

1
2
3
4
5
6
7
var dynamicLabel: UILabel = UILabel()
dynamicLabel.frame = CGRectMake(50, 150, 200, 21)
dynamicLabel.backgroundColor = UIColor.orangeColor()
dynamicLabel.textColor = UIColor.blackColor()
dynamicLabel.textAlignment = NSTextAlignment.Center
dynamicLabel.text = "test label"
self.view.addSubview(dynamicLabel)

 

UITextField

UITextField class is use to display editable text input area.

UITEXTFIELD-SWIFT-PROGRAMMATICALLY

1
2
3
4
var dynamicTxtField: UITextField = UITextField()
dynamicTxtField.frame = CGRectMake(50, 70, 200, 30)
dynamicTxtField.backgroundColor = UIColor.lightGrayColor()
self.view.addSubview(dynamicTxtField)