I’m building my first app in Swift. I have RestaurantViewController
. Half of the screen is filled by restaurant name, description, logo, atd.
And under this I have UICollectionView()
, filled with restaurant Coupons. Everything works fine, but I wanna disable scrolling INSIDE the CollectionView
, and allow to scroll in entire page – so when user scrolls in coupons, whole page is scrolling down and next coupons are showed.
How can I do it?
IMAGE – I wanna this after scroll
Coupons are loaded via API, so they are available few moments after setupUI() etc.
My code inside setupUI():
...
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
self.couponsCollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
couponsCollectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CouponCollectionCell.reuseIdentifier)
couponsCollectionView!.alwaysBounceVertical = true
couponsCollectionView!.isScrollEnabled = false
...
I am not using Storyboard, just all programmatically. Also with UIKit and SnapKit (external library)
My SnapKit code for create constraints in screen:
...
couponsCollectionView!.snp.makeConstraints { make in
make.top.equalTo(couponsTitle.snp.bottom).offset(0)
make.left.equalTo(0)
make.width.equalToSuperview()
make.leading.trailing.bottom.equalToSuperview()
}
...
Thank you!!!
2
Answers
You can start with adding the content top of UICollectionView as a header and rest as cells of UICollectionView
An example is as follow
I’d add the restaurant information (logo, name, …) inside a UICollectionViewHeader so everything scrolls smoothly, as suggested by @clawesome and @Muhammad
Following your approach and if we try to achieve the desired effect without using a header to include the restaurant information, I created a very simple project to simulate the behaviour.
Instead of constraining the collection view at the bottom of the restaurant information, you could pin it to the top, and update the contentInsets and add the necessary padding. Like this you achieve the same effect as it was starting just under the restaurant information.
Then you could implement
func scrollViewDidScroll(_ scrollView: UIScrollView)
and update the constraints of the restaurant information according to the amount the user has scrolled.200
is the height of the restaurant information view and the restaurantViewAnchorConstraint is aNSLayoutConstraint
declared as a property as:var restaurantViewAnchorConstraint: NSLayoutConstraint!
Remember to first add the collection view as a subview, not after the restaurant information, if not the collection view will hide all this information.
Video proof