Barkley
Barkley

Reputation: 6693

Off center center.x when working with stackview

enter image description here

I've got a stack view and I'm wanting when the user clicks on one of the buttons a little "bar" view centers underneath it (the view is outside of the stack view). I had this working before I layed out the buttons with autolayout by just setting

movableView.center.x = newView.center.x

and animating it. Now with the buttons in the stack view the movableView's center X does not line up with the buttons' center x's. It's like 1/3 way off centered.

The movable view itself has no autolayout on it.

What is the cause of this and how can I align the center x of views that have auto layout in play?

Upvotes: 0

Views: 448

Answers (1)

creeperspeak
creeperspeak

Reputation: 5523

Without more information this is my best guess as to what the issue may be.

The center attribute is based on the view's frame, which means that it is using the superview (in this case the UIStackView) coordinate system. If your UIStackView's frame.origin.x is not at 0, which is how it appears in your screenshot, you will need to adjust your movableView.center.x accordingly. This could be as simple as:

movableView.center.x = newView.center.x + stackView.frame.origin.x

Another option would be to convert the center to the main view's coordinate system, like this:

movableView.center.x = newView.convert(newView.center, to: self.view).x

Upvotes: 4

Related Questions