swift2 无法在UICollectionView中调整单元格间距

uxhixvfz  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(236)

我已经在Swift中实现了collectionView,
但是当我在更大屏幕的iPhone上检查时,电池之间的间距会增加。
以下是iphoen 5s x1c 0d1x 1的示例:
下面是iPhone 6

2的例子:
下面是我xcode设计

3
我在哪里犯了错误?有谁能帮我吗?

提前感谢您!

t8e9dugd

t8e9dugd1#

这解决了我的问题。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
        return CGSizeMake((UIScreen.mainScreen().bounds.width-15)/2,208); //use height whatever you wants.
    }
wko9yo5t

wko9yo5t2#

我认为您应该使用自动布局,使您的单元格宽度为CollectionView宽度的一半,并减去一些点,但我不确定这是否可以在故事板中设置,我主要在代码中进行设置,使用“collectionViewFlowLayout.setItemSize”设置相对于屏幕宽度的项目大小,或者UICollectionViewDelegateFlowLayout也可以;

r9f1avp5

r9f1avp53#

这样做:

func collectionView(collectionView: UICollectionView,
        layout collectionViewLayout: UICollectionViewLayout,
        sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
    {
           collectionData.contentInset=UIEdgeInsetsMake(0,0,0,0)
        let screensize:CGRect=UIScreen.mainScreen().bounds
        let width=screensize.width

        if (width==320)
        {
            let size:CGSize=CGSizeMake(129,140)
            collectionData.contentInset=UIEdgeInsetsMake(0,10,0,10)
            return size
        }
        else if(width==375)
        {
            let size:CGSize=CGSizeMake(166,181)
            collectionData.contentInset=UIEdgeInsetsMake(0,0,0,0)
            return size
        }
        else if(width==414)
        {
            if(UIDevice.currentDevice().orientation .isLandscape)
            {
                let size:CGSize=CGSizeMake(300,185)
                collectionData.contentInset=UIEdgeInsetsMake(0,0,0,0)
                print("com,ing inside orientatiom");
                return size

            }
            let size:CGSize=CGSizeMake(177,185)
            collectionData.contentInset=UIEdgeInsetsMake(0,0,0,0)
            return size
        }
        let size:CGSize=CGSizeMake(358,292)
        return size

    }
dwbf0jvd

dwbf0jvd4#

你可以为所有设备调整公共空间-目标C版本

- (CGSize)collectionView:(UICollectionView *)collectionView 
              layout:(UICollectionViewLayout *)collectionViewLayout 
   sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

   CGFloat height = self.view.frame.size.height;
   CGFloat width  = self.view.frame.size.width;
   // in case you you want the cell to be 40% of your controllers view
   return CGSizeMake(width*0.4,height*0.4)
 }

相关问题