mars
mars

Reputation: 1641

Updating constraints programmatically

Situation is like I have a view with four buttons

enter image description here

There comes a condition when button with text Search Community should be hidden and width of Options button should get increased

enter image description here

Using Constraints for the first time in my project, I am not getting how to achieve this. Set of constraints added on both these buttons would be clear from the following two images.

enter image description here

enter image description here

Upvotes: 0

Views: 508

Answers (2)

Catalina T.
Catalina T.

Reputation: 3494

The problem I see with your setup is that you have this constraint between the 2 buttons of equal width. This is true in the first case but when you want to hide one of them, it is not anymore.

So, you will need to rethink your constraints a bit. Maybe instead of the equal width constraint, you could use a static width constraint one the first button(the left one, that you want to hide). Then the second one, will just have a horizontal space constraint to the first one, and a trailing space to the superView.

Then you make an outlet in the VC for the width constraint of the first button and when you want to hide it you do something like this:

self.searchButtonWidthConstraint.constant = 0 
UIView.animateWithDuration(0.3, animations: {  () -> Void in
       self.view.layoutIfNeeded() // if you want to animate the constraint change
})

Let me know if you have questions. Good luck and hope it works out!


Update


For the landscape use case, you could listen to the orientation change notification, to update the width constraint of the button

-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    self.searchButtonWidthConstraint.constant = LANDSCAPE_WIDTH
    UIView.animateWithDuration(duration, animations: {  () -> Void in
           self.view.layoutIfNeeded() // if you want to animate the constraint change
    })
} 

Upvotes: 1

Chetan Prajapati
Chetan Prajapati

Reputation: 2307

enter image description here

Add constraint to 1st Button

  1. Leading Space To NewView(gray colored)
  2. Bottom space to NewView
  3. Top Space to Topbutton (blue colored in your 1st and 2nd image)
  4. Width (from Bottom - Right portion )enter image description here

Add Constraint to 2nd Button

  1. Trailing Space to NEwView
  2. Bottom space to NewView
  3. Top Space to Topbutton (blue colored in your 1st and 2nd image)
  4. Horizontal space FirstButton ( Search Community )
  5. Width

Upvotes: 0

Related Questions