Delegation in iOS & Build Interface Programmatically
I am starting a series of posts summarizing the key concepts in Swift & Cocoa Touch learnt lately, to prepare for an iOS app project.
Delegation
To say it easily, a delegate helps to do some work that the delegator, or delegating object, sends to it under certain conditions. To implement a delegation pattern, there are three major steps:
- Adopt a particular delegation protocol at the beginning of the class. For example,
class AddActivityViewController: UIViewController, UITextFieldDelegate
Note this does not mean AddActivityViewController
inherits UITextFieldDelegate
. Swift does not support multiple inheritance, similar to Objective-C.
- Link an object on interface to that delegate.
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
- Implement delegate functions, so that the delegate would do certain things under a particular condition.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
Build Interfaces Programmatically
Coding out the user interfaces rather than drawing them on the storyboard has many advantages, one of which is that version control systems, such as git
, would be more easily applied. Here are some basic functions of building an UIView
, for instance:
- An initializer, similar to constructor in C++/Java. It can be used to
- create labels, text fields, buttons, etc.
- link their triggered actions to functions (similar target-action pattern when using storyboards, that is,
@IBAction
) - Add these objects to the interface
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)
addSubview(button)
layoutSubviews()
function, which is called automatically to update interface layouts and could be used to set button frames, etc.- A Property Observer can sometimes be useful for updating the interface. It keeps track of a variable’s value and calls a function immediately when it’s changed.
var rating = 0 {
didSet {
setNeedsLayout() // force a layout update prior to the next drawing update
}
}
One last thing, never forget to connect the un-designed object on the storyboard (such as an empty UIView
) to the custom class in Identity inspector!