Create Elements Using Code in Swift

Recent versions of Xcode provide a sleek interface to be able to drag and drop elements onto the view. Some developers may want to learn how to create elements using code in Swift 3 rather than using the interface.

The UIKit provides a library that enables developers to create elements and add them to a project. With that said, you can create elements using syntax such as UILabel and UIButton.

An example of programmatically creating a UILabel can be demonstrated within the viewDidLoad() method of the ViewController.swift class.

Define a label constant, adding in the CGRect structure, which contains the location and dimensions of a rectangle.

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))

The rectangle can then be positioned on the view using the CGPoint structure and setting it to the center property of the label.

label.center = CGPoint(x: 160, y: 285)

Add and align a label using the text and textAlignment properties respectively.

label.text = "This is a test label"
label.textAlignment = .center

Finally, add the label to the view using addSubview of the ViewController.swift class.

self.view.addSubview(label)

In summary, the function might look like the following:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
        
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
    label.center = CGPoint(x: 160, y: 285)
    label.text = "This is a test label"
    label.textAlignment = .center
    self.view.addSubview(label)
}

The same steps can be used to add a UIButton.

let button = UIButton()
button.setTitle("Click Me!", for: .normal)
self.view.addSubview(button)

With a button, additional functionality might be required when the button is pressed. Swift provides an addTarget method.

button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)

A buttonAction() function can then be added, which can contain some code to run when the button is pressed (touchUpInside). This is not too dissimilar from adding IBActions using the Interface Builder Xcode provides.

An example of some code running when the button is pressed can be seen below. Here an alert box is presented.

func buttonAction(sender: UIButton!) {
    let alertController = UIAlertController(title: "Alert", message: "Here is an alert", preferredStyle: UIAlertControllerStyle.alert)
        
    let destructiveAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.destructive) {
        (result : UIAlertAction) -> Void in
    }
        
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
        (result : UIAlertAction) -> Void in
    }
        
    alertController.addAction(destructiveAction)
    alertController.addAction(okAction)
    present(alertController, animated: true, completion: nil)
}

Firstly an alertController constant is assigned a UIAlertController. Constants are then added to provide the ‘OK’ and ‘Cancel’ button actions.

These actions are added to the alert controller.

alertController.addAction(destructiveAction)
alertController.addAction(okAction)

Lastly, the UIAlertController is shown in the view using present().

present(alertController, animated: true, completion: nil)

Note: This article is based on iOS 10 and Swift version 3.