简体   繁体   中英

Animate contraint change when user is scrolling in tableview

I have a view which serves as a container for another 2 views(one view which takes 1/4 of the screen and a table view which takes 3/4 of the screen). What I want is that when the user scrolls up(swipe direction) the tableview, the table view will smoothly go up (up to the screen) and go down when users scrolls down(swipe direction).

So far I have managed so that the tableview goes up but it does it too sudden and can't make it go down. Here is how i do it: viewViewTopConstraint is the tableview top constraint to container top constraint

extension StatsOverlayViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
    if scrollView == statsTableView {
        let scrolledOffset = scrollView.contentOffset.y

        while viewViewTopConstraint.constant > 0  && viewViewTopConstraint.constant < 69 {
            print("scrolling with offset\(scrollView.contentOffset.y)")
                self.viewViewTopConstraint.constant -= scrolledOffset
        }
    }
}

func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if scrollView == statsTableView {
        if  viewViewTopConstraint.constant < 0 {
            viewViewTopConstraint.constant = 0
        } else if viewViewTopConstraint.constant > 69 {
            viewViewTopConstraint.constant = 69
        }
    }
}

}

Edit:

Problem with putting the view back down was due to the scrollview.bounces = true and the wrong use of the while loop Code that works is :

       func scrollViewDidScroll(scrollView: UIScrollView) {
    if scrollView == statsTableView {
        let scrolledOffset = scrollView.contentOffset.y
        UIView.animateWithDuration(0.2, animations: {
            if scrolledOffset > 0 {
                self.viewViewTopConstraint.constant = 0
            } else {
                self.viewViewTopConstraint.constant = self.viewViewTopConstraintOriginalValues
            }
            self.view.layoutIfNeeded()
        })
    }
}

You need to call self.view.layoutIfNeeded within UIView.animate block

UIView.animate(withDuration: 1) { 
    self.view.layoutIfNeeded
}

Add this code right after you change your constraint. If you want a little bit more control on your animation, use this

UIView.animate(withDuration: 1, delay: 0, options: [.curveEaseInOut], animations: {
    self.view.layoutIfNeeded
}, completion: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM