skip to Main Content

I have a custom UIView class named UpperInformationUIView, and I’m trying to expand and collapse it based on different states (default, shrinked, and expanded). The collapse function seems to be working fine, but I’m facing an issue when trying to expand the view.

Here’s my code snippet:


private func expandView() {
    switch viewHeightState {
    case .defaulted:
        viewHeightConstraint.constant = maxHeight
        viewHeightState = .expanded
    case .shrinked:
        viewHeightConstraint.constant = defaultHeight
        viewHeightState = .defaulted
    case .expanded:
        return // Already expanded
    }

    UIView.animate(withDuration: 2) {
        self.layoutIfNeeded()
    }
}

I want the view to expand from the current state to either maxHeight or defaultHeight, depending on the current state. But the view’s center position is moving to the bottom first, and then it is stretching vertically, instead of only expanding downward as intended.

I’ve also set the top space constraint to 0 in the storyboard, but the problem persists.

Could anyone please guide me to find what I’m missing or what’s going wrong? Thank you!

2

Answers


  1. You need to re-layout the parent view

    UIView.animate(withDuration: 2) {
        self.superview?.layoutIfNeeded()
    }
    
    Login or Signup to reply.
  2. Your Code is Fine . you just forgot to mention yoit parrentView .
    Just modify your self.layoutIfNeeded() and replace it by self. self.superview.layoutIfNeeded()
    hope it will work .
    if you face issue again please mention then .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search