简体   繁体   中英

Dynamically set collection view cell size on different devices

I am trying to achieve horizontal swiping with a collection view that should have an image view centered on each swipe

I can do this on one device size by manually setting the cell height + width to the device size

However when I change device, the cell size is disproportionate

How can I maintain the cell size to change with each device? I want the cell to take up 100% of width and height

Thanks

My advice: don't. What you are describing is much more like a UIPageViewController than a collection view. And with a UIPageViewController, what you are describing is trivial — it happens, in effect, automatically.

   func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{

        return CGSizeMake(self.view.frame.size.width) , (self.view.frame.size.height))
}

Although I am agree with Matt answer. But you can do it with this code as well. you don't need to create extension. you just need override this collection view delegate method

Create a custom flow layout for your collection view and assign the delegate to your view controller.

This will allow you to dynamically change your layout based on the requirements (in your case, a different size per device). Specifically, the collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) method allows you to change the cell size for each item. It will look something like this:

extension ViewController : UICollectionViewDelegateFlowLayout {
    func collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize {
        return CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
    }
}

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