Uicollectionview单元格宽度问题iOS 10

时间:2016-11-06 18:20:30

标签: ios iphone swift xcode uicollectionview

我有一个集合视图控制器,我设置如下:

class r : UICollectionViewCell {

    override var bounds: CGRect {
        didSet {
            contentView.frame = bounds
        }
    }
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "1", for: indexPath) as? r

        cell.backgroundColor = UIColor.red

        return cell


    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 5
    }

我希望单元格的宽度等于屏幕的宽度,因此在故事板中我编辑了单元格的宽度:

enter image description here

但我有一个问题:

如果我在iPhone 6模拟器上执行它,我会得到这个(这是我想在所有设备上获得的):

enter image description here

但如果在iPad Pro上执行,我会得到:

enter image description here

我不明白为什么。 你能救我吗?

P.S我不想出于某种原因使用tableview

4 个答案:

答案 0 :(得分:1)

在iOS 10中,函数原型存在细微差别: 这是sizeAtItemAtIndexPath的Swift3.0 Delegate方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        let screenRect: CGRect = UIScreen.main.bounds
        let screenWidth: CGFloat = screenRect.size.width
        let screencellHeight: CGFloat = screenRect.size.height
        let cellWidth: CGFloat = screenWidth / CGFloat(2)
        let cellHeight:CGFloat = screencellHeight / CGFloat(10.0)
        let size: CGSize = CGSize(width: cellWidth, height: cellHeight)
        return size
    }

答案 1 :(得分:1)

如果您使用约束,那么首先应用相同宽度约束的单元格以及故事板,您应检查inspect编辑器中的水平和垂直的所有设置的集合视图设置..

答案 2 :(得分:0)

我假设你已经为某个地方设置了一个固定的宽度。也许是约束。动态设置:

  • 符合UICollectionViewDelegateFlowLayout

并覆盖:

@objc(collectionView:layout:sizeForItemAtIndexPath:)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let desiredNumberOfCollumns: CGFloat = 1
    let width = collectionView.frame.width / desiredNumberOfCollumns
    let height = 100 // your desired height

    return CGSize(width: width, height: hight)
}

答案 3 :(得分:0)

我认为你正在使用约束。如果是,那么您只需要在约束中修复单元格的宽度。

除非你没有改变。无论你在哪里设置宽度ind委托。它将保持不变。