deathAdder
deathAdder

Reputation: 33

Changing height of stack through code and then resetting it in iOS swift

I have a stackview whose height is 250. I want to program:

  1. When the button is tapped, the stack should go to the top of screen.
  2. Then after a few seconds it should go back to its height of 250, which Will be done via dispatchque.main.asynafter

How can I get it to go to the top of the screen & then reset it to its original height? The stack I want to go upto the top of the superview

Upvotes: 0

Views: 178

Answers (1)

Tarun Tyagi
Tarun Tyagi

Reputation: 10112

  1. Make sure your stackViewHeightConstraint has a priority of 999.
  2. Create another constraint like stackView.topAnchor equalTo superview.topAnchor (DO NOT ACTIVATE IT).
  3. When you hit the button for going to Expanded state, activate this top-to-top constraint.
  4. When you want to go back to Normal state, deactivate this top-to-top constraint.

UPDATE

class ViewController: UIViewController {
    @IBOutlet var stackView: UIStackView!

    // Assumes that stackView is added as a subview in self.view
    private lazy var topToTopConstraint: NSLayoutConstraint = {
        stackView.topAnchor.constraint(equalTo: self.view.topAnchor)
    }()

    @IBAction func expand() {
        NSLayoutConstraint.activate([topToTopConstraint])
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in
            guard let self = self else { return }
            NSLayoutConstraint.deactivate([self.topToTopConstraint])
        }
    }
}

Upvotes: 2

Related Questions