Reputation: 83
I'm confused how the following code uses the view
property to access the subView method in the viewDidLoad()
function. The viewDidLoad
function provides access to the view
property, but why is the addSubView
method accessed from a property and not an instance?
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 16, y: 16, width: 200,
height: 44))
view.addSubview(label) // Adds label as a child view to `view`
}
Upvotes: 0
Views: 51
Reputation: 131511
A UIViewController
has a property view
. In swift, you can usually skip the "self" prefix when referring to properties of the current object.
The line view.addSubview(label)
is equivalent to:
self.view.addSubview(label)
Or, to make it even clearer what it's doing by using a local variable:
let aView = self.view
aView.addSubview(label)
Upvotes: 1
Reputation: 1078
The view is a property of the viewcontroller, but it is an instance of UIView, which has a set of subviews, and you can add to this set by calling addSubview() on any UIView instance. https://developer.apple.com/documentation/uikit/uiview
Upvotes: 2