【问题标题】:Create equal space between cells and between margins and cells UICollectionView在单元格之间以及边距和单元格 UICollectionView 之间创建相等的空间
【发布时间】:2018-10-20 20:07:25
【问题描述】:

我有一个 UICollectionView。在某些设备上,细胞紧贴设备的边缘,而中心有很大的间隙。我尝试过更改插图和最小间距,但两者都不起作用。我在情节提要中创建了这个,所以我没有与格式相关的代码。如何使单元格之间的空间等于外部单元格和边缘之间的空间,以便中间没有巨大的间隙?谢谢。

图像的边缘是设备的精确边缘

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    假设您使用UICollectionViewFlowLayout 并且您的单元格具有固定大小:

    自定义单元格代码:(我添加了一些阴影和圆角,忽略它)

    import UIKit
    
    class CollectionViewCell: UICollectionViewCell {
        override init(frame: CGRect) {
            super.init(frame: frame)
    
    
            layer.shadowColor = UIColor.lightGray.cgColor
            layer.shadowOffset = CGSize(width: 0, height: 2.0)
            layer.shadowRadius = 5.0
            layer.shadowOpacity = 1.0
            layer.masksToBounds = false
            layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: contentView.layer.cornerRadius).cgPath
            layer.backgroundColor = UIColor.clear.cgColor
    
            contentView.layer.masksToBounds = true
            layer.cornerRadius = 10
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

    查看控制器代码:

    import UIKit
    
    private let reuseIdentifier = "Cell"
    
    class CollectionViewController: UICollectionViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            /// Class registration
            collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
            /// Expected cell size
            let cellSize = CGSize(width: 120, height: 110)
    
            /// Number of columns you need
            let numColumns: CGFloat = 2
            /// Interitem space calculation
            let interitemSpace = ( UIScreen.main.bounds.width - numColumns * cellSize.width ) / (numColumns + 1)
    
            /// Setting content insets for side margins
            collectionView.contentInset = UIEdgeInsets(top: 10, left: interitemSpace, bottom: 10, right: interitemSpace)
    
            /// Telling the layout which cell size it has
            (self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = cellSize
        }
    
        override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 10
        }
    
        override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
            cell.backgroundColor = .white
            return cell
        }
    }
    

    结果如下:

    【讨论】: