0

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`
}

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.