简体   繁体   中英

Swift change UICollectionView height when scrolling

I'm looking to do the following, see the 2 pictures below. I have a UICollectionView and a UILabel on top of it (the green area).

I would like, when scrolling down, to decrease the height of the collection and increase the height of the UILabel scrolling up (similar with what safari does on iPhone with the search bar when scrolling up and down). What I've tried is the following:

func scrollViewDidScroll(scrollView: UIScrollView!) {
    collectionView.frame=CGRectMake(0.0, collectionView.frame.origin.y-1, 375, collectionView.frame.height+1);
}

It's starting ok at first, the height is increasing, but suddenly the height of the UICollectionView gets smaller and then starts increasing again. And then it does the same

Here below I've displayed the results of print(collectionView.frame)

Is there a bug in my solution ? Is there another way to achieve that ? Is something related to constraints ?

Thanks.

CC

(0.0, 174.0, 375.0, 493.0)
(0.0, 173.0, 375.0, 494.0)
(0.0, 172.0, 375.0, 495.0)
(0.0, 190.0, 375.0, 477.0)
(0.0, 189.0, 375.0, 498.0)
(0.0, 188.0, 375.0, 499.0)
(0.0, 187.0, 375.0, 500.0)

在此处输入图片说明

The proposed solution in your scrollViewDidScroll is omitting the direction of the scroll - basically you are saying: move the collection view up and increase its size whenever the user scrolls . But you are not saying whether it's up or down. I handle the direction by saving the last scrollView's contentOffset.y and then doing simple if:

if self.lastScrollViewContentOffset > scrollView.contentOffset.y {
    // mumbo jumbo when scrolling up
} else {
    // mumbo jumbo when scrolling down
}

Also mind that this method is one of two that you should use to make it smooth and continuous. This method is called after the scrolling has happened:

The delegate typically implements this method to obtain the change in content offset from scrollView and draw the affected portion of the content view.

But if you drag only half way you may find yourself in inconsistent state (I know this because I implemented similar thing), so also implement delegate method scrollViewDidEndDragging where you need to bear in mind that it may not decelerate and thus you'll need to add additional animation to make the UI consistent.

Add height constraint to your label or collectionView. Create an IBOutlet for that constraint and then change it in scrollViewDidScroll using the contentOffset as suggested by Michal.

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