Using .center to move a subview within its parent

Hello All!

Everything I've read (Xcode online docs, iOS programming manuals, etc.) indicate that the best way to move a subview within its parent is to change its .center (.x or .y) property.

I have been trying to figure this out for a bit now and the only way I can make a subview move is to change the .frame.orgin of its parent, which moves all the subviews - not what I want.

Why can't I make changing .center work in the following code snipet (self is the parent View Controller)?

// Load POI menus
let poiMenus = Bundle.main.loadNibNamed("POIMenuViews", owner: nil)!
let primaryPOIMenu = poiMenus[0] as! UIStackView
self.view.subviews[0].addSubview(primaryPOIMenu)    // works down to here
primaryPOIMenu.center.x += 88   // This NO WORKY!!!  Why???

NOTE: The primaryPOIMenu.center.x IS changing (confirmed) but the subview is not moving. I tried using .center similarly in another place and that subview didn't move either.

I'm very confused - this should be simple.

Thanks in advance.

Answered by wmfrey3331 in 695762022

Well, I solved the problem days ago using Outlets to grab references to the menu objects in the NIB and also used constraints position and then reposition them, rather than trying to manipulate the 'center' properties.

It also had something to do with the way I was setting up the NIB positioning criteria in the UI Builder - still haven't quite figured that out yet...

Thanks to all for your input!

Take care!

As far as I tried your code, the statement primaryPOIMenu.center.x += 88 works as expected.

(The background color of POIMenuViews is set to system yellow.)

But many things depend on the settings of your storyboard and xib.

What do you get when you comment out the line modifying center?

        //primaryPOIMenu.center.x += 88   // This NO WORKY!!!  Why???

Thank you. I thought it should work. I must be doing something else wrong.

I'll keep at it. It's got to be something simple.

Take care!

Sorry - I didn't see your question at the bottom until just now.

If I comment out that line of code, the subview remains where it shows up in the parent - at origin 0,0.

Your suggestion that my problem may lie in the xib is something I need to look into. I am pretty new to all this, so I might be missing something.

Thank you, again!

Accepted Answer

Well, I solved the problem days ago using Outlets to grab references to the menu objects in the NIB and also used constraints position and then reposition them, rather than trying to manipulate the 'center' properties.

It also had something to do with the way I was setting up the NIB positioning criteria in the UI Builder - still haven't quite figured that out yet...

Thanks to all for your input!

Take care!

Using .center to move a subview within its parent
 
 
Q