Creating Clean Blocks of Code for Custom Views

You want to programmatically create a custom view. Then you want to fill it up with buttons, labels, and all different kinds of subviews. If you aren’t careful, your code can get messy quick. In order to battle this, a popular technique is used by creating everything as stored properties and initializing them as closures.

Regular declaration

//Initialize a button instance
let awesomeButton = UIButton() 
//Start modifying its properties
button.setTitle("Press for awesomeness", for: .normal)
button.backgroundColor = .blue
button.setTitleColor(.white, for: .normal)
//Initialize a label instance
let awesomeLabel = UILabel() 
//Start modifying its properties
label.textAlignment = .center
label.text = "I'm awesome"

The more concise way

let awesomeButton: UIButton = {
  let button = UIButton()
  button.setTitle("Press for awesomeness", for: .normal)
  button.backgroundColor = .blue
  button.setTitleColor(.white, for: .normal)      
  return button
}()

let awesomeLabel: UILabel = {
  let label = UILabel()
  label.textAlignment = .center
  label.text = "I'm awesome"
  return label
}()

At first this might look like a computed property. But then you see the () at the end. It is a stored property, and the () at the end is initializing it as a closure. When you create complex custom views, this adds both to reusability and code aesthetics.

And why 2 variables for one object?

awesomeButton and button
awesomeLabel and label

Technically you could use the same name. But the standard, most readable way is to have the first variable describe and the second variable represent the type.

Leave a Comment

Your email address will not be published. Required fields are marked *