enesefuu
enesefuu

Reputation: 409

Position of a view with .zero frame

I have a view (VIEW A). I need to get it's position inside of it's superview (ideally a CGPoint for it's Center X and Center Y).

This would be easy, except that when I add VIEW A into the view, I set it's frame to be .zero, and use NSLayoutConstraint anchors to position it. So later, when I want to get it's frame (I've also tried it's bounds), it comes back as (0,0,0,0).

VIEW A is visible and positioned inside it's superview...so it has some X/Y coordinates and width/height right? How do I access these values?

Upvotes: 1

Views: 3395

Answers (2)

nyrd
nyrd

Reputation: 498

A safe place to get access to updated frames is on viewDidLayoutSubviews after the call to super's implementation

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // Here we have access to updated frames
}

If you are adding the subview, say, in viewDidLoad, then the UIViewController hasn't make any calculation for the frames. It just has the rules (constraints) describing the relations between its views. In the lifecycle of a UIViewController, viewDidLayoutSubviews is the point where the frame calculations has already been done and it's safe to access them. You can even calculate some frames yourself after the super call.

Upvotes: 2

Code Different
Code Different

Reputation: 93181

Call setNeedsLayout() AND layoutIfNeeded() on the parent view:

let myView = UIView(frame: .zero)
myView.backgroundColor = .red
myView.translatesAutoresizingMaskIntoConstraints = false

view.addSubview(myView)
myView.topAnchor.constraintEqualToSystemSpacingBelow(view.topAnchor, multiplier: 1).isActive = true
myView.leftAnchor.constraintEqualToSystemSpacingAfter(view.leftAnchor, multiplier: 1).isActive = true
myView.widthAnchor.constraint(equalToConstant: 50).isActive = true
myView.heightAnchor.constraint(equalToConstant: 50).isActive = true

view.setNeedsLayout()
view.layoutIfNeeded()
print(myView.frame)

Upvotes: 1

Related Questions