简体   繁体   English

在不同设备上动态设置集合视图单元格大小

[英]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 我希望单元格占用宽度和高度的100%

Thanks 谢谢

My advice: don't. 我的建议:不要。 What you are describing is much more like a UIPageViewController than a collection view. 您所描述的更像是UIPageViewController而不是集合视图。 And with a UIPageViewController, what you are describing is trivial — it happens, in effect, automatically. 使用UIPageViewController,您所描述的内容微不足道-实际上是自动发生的。

   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. 特别是, collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath)方法允许您更改每个项目的单元格大小。 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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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