Junior — Middle
How is data binding to user interface elements implemented in UIKit?
sobes.tech AI
Answer from AI
In UIKit, data binding with UI elements is usually implemented manually, as unlike SwiftUI, there is no built-in two-way binding mechanism.
Main methods:
- Direct assignment of values: for example, setting the text in a UILabel via the
textproperty. - Using delegates and target-action to handle events and update data.
- KVO (Key-Value Observing) — allows observing property changes and updating the UI.
- Using third-party libraries, such as RxSwift for reactive binding.
Example of simple binding:
class ViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
var name: String = "Ivan" {
didSet {
nameLabel.text = name
}
}
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = name
}
}
Here, when the name property changes, the text in UILabel is updated.