Neko
Neko

Reputation: 589

How to Update NSLayoutConstraint in StoryBoard?

I created 2 Button in my superView , Now I want change the @IBOutlet weak var bottomLayOut: NSLayoutConstraint! depend on the user role .

the example is: if the user is a agent role but not a teacher role I want update the NSLayoutConstraint 's second item from Teacher Entry .bottom to AgentEntry button's bottom .

enter image description here is that posible?

Update :

solve this by turn translatesAutoresizingMaskIntoConstraints to true: e.g : teacherBtn.translatesAutoresizingMaskIntoConstraints = true than, we can use both constraints and code to change teacherBtn's frame

Upvotes: 0

Views: 686

Answers (1)

Charles Srstka
Charles Srstka

Reputation: 17050

Two ways I can think of to do this off the top of my head:

  1. Set up the constraints programmatically. Create a property containing the current constraints on the buttons, and then you can do something along the lines of (disclaimer: written in Chrome, may contain typos, edit as appropriate):

` if let constraints = self.buttonConstraints { NSLayoutConstraint.deactivate(constraints) }

let views: [String : UIView] = ["Agent" : self.agentButton, "Teacher" : self.teacherButton]

let newConstraints: [NSLayoutConstraint] = {
    switch role {
    case .teacherAndAgent:
        self.teacherButton.isHidden = false
        self.agentButton.isHidden = false
        return NSLayoutConstraint.constraints(withVisualFormat: "V:[agent]-[teacher]-|", metrics: nil, views: views)
    case .teacherOnly:
        // you get the idea
    case .agentOnly:
        // ditto
    }
}()

NSLayoutConstraint.activate(newConstraints)
self.buttonConstraints = newConstraints`
  1. What might be simpler, though, is to use a UIStackView to hold your buttons. On current macOS at least, NSStackView automatically adjusts the layout based on which of its views are hidden; if UIStackView on iOS behaves the same way, it may do a lot of the work for you without having to manually fuss with layout constraints.

Upvotes: 2

Related Questions