UICollectionViewCell已经偏移了

时间:2017-07-29 18:24:46

标签: ios uicollectionview

在我的今日小工具中,我使用了UICollectionView,其中包含一些不同大小的单元格。

let layout = UICollectionViewFlowLayout.init()
layout.scrollDirection = UICollectionViewScrollDirection.vertical;
collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.green
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")

self.view.addSubview(collectionView)

然后,我现在创建具有一些占位符颜色的单元格:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
    return CGSize.zero
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if (pokemon.count == 0) {
        if (indexPath.row == 1) {
            return CGSize.init(width: self.view.frame.size.width, height: 220)
        } else {
            return CGSize.init(width: self.view.frame.size.width, height: 110)
        }
    } else {
        if (indexPath.row == 0) {
            return CGSize.init(width: self.view.frame.size.width, height: 110)
        } else {
            return CGSize.init(width: self.view.frame.size.width, height: 56)
        }
    }
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if (pokemon.count == 0) {
        return 2
    } else {
        return pokemon.count+1
    }
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

    if (indexPath.row == 0) {
        cell.backgroundColor = UIColor.yellow
    } else if (indexPath.row == 1) {
        cell.backgroundColor = UIColor.red
    } else if (indexPath.row == 2) {
        cell.backgroundColor = UIColor.purple
    }

    return cell
}

现在,发生的事情是我的细胞有左侧偏移,我无法弄清楚为什么会这样。我附上了行为的截图。我尝试使用直接包含的最小距离设置布局,但这并没有任何效果。有什么想法吗?

a screenshot

1 个答案:

答案 0 :(得分:0)

我怀疑 automaticAdjustsScrollViewInsets 设置为true。尝试在viewDidLoad中将此设置为false。