0

I use Autolayout for a fairly complex Menu and really need it. All Buttons, UIViews etc. of my Menu are in a separate UIView called "menuSubview".

If the user presses a button the whole "menuSubview" shifts to another position to reveal other parts of the menu. Sometimes the buttons in the menuSubview move as well. I always save the "Menu State" (with Userdefaults in the get-set variable "lastMenu") and have a function to set the alphas and centers according to the saved "Menu State".

I tried calling the "openLastMenu" function in viewDidAppear, viewDidLayoutSubview - all the "viewDid" functions of the ViewController. The "menuSubview" center and alphas of the buttons always behave as expected... but the centers of the buttons simply won't - no matter what "viewDid" I call the function in.

(the code is a lot more complex - I boiled it down to debug and state my point)

override func viewDidAppear(animated: Bool) {

    if lastMenu != nil {openLastMenu()}

}

func openLastMenu(){

    menuSubview.center.x = view.center.x //works
    menuSubview.center.y = view.center.y + 200 //works

    button1.center.x = view.center.x - 50 //why you no behave???
    button2.center.x = view.center.x + 50 //why you no behave???
    button3.alpha = 0 //works
    button4.alpha = 0 //works

}

For debugging I even made a button Subclass to fetch the "center" values with a "didSet" if they change. Seems like after taking the correct values they change once more to their Autolayout-Position.

...oh and ignoring the constraints with "translatesAutoresizingMaskIntoConstraints" on the buttons always fucks up the whole menu. I'm starting to get crazy here :)

1 Answers1

0

If you position views using autolayout, any changes to the frame, like what you do here with the center property, will be ignored.

What you need to do is identify the constraints that are you need to change to move the views in the desired position. Example:

You want to move button1 50 points to the left of view.center. Assuming view is the superview of menuSubview, you would

1) deactivate the the constraint responsible for button1's horizontal placement. How you do this mainly depends on whether you created the constraints in code or Interface Builder. The latter will require you to create outlets for some of the constraints.

2) create a new constraint between button1's centerX anchor and view's centerX anchor with a constant of -50, like so (iOS 9 code)

button1.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor, constant: -50.0).active = true

robinkunde
  • 1,005
  • 9
  • 12