UICollectionView自我调整单元格。 Insert / reloadData打破布局

时间:2015-07-12 10:29:08

标签: swift uicollectionview uicollectionviewlayout collectionview flowlayout

把这个问题写成我的最后一招,现在被困在这几天了。我正在尝试使用UICollectionViewFlowLayout实现自定义单元格。一切似乎工作正常,直到我reladData()insertItemsAtIndexPaths()位于collectionView的底部。

这是我的手机:

class FooFoo: UICollectionViewCell {

var label: UILabel!
var text: String! {
    didSet {
        label.text = text
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)

    setupView()
    setupConstraints()
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setupView() {
    self.contentView.backgroundColor = UIColor.yellowColor()

    label = ({
        let view = UILabel()

        view.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.contentView.addSubview(view)

        return view
    })()
}

func setupConstraints() {
    self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-100-[childView]-100-|", options: nil, metrics: nil, views: ["childView": label]))
    self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[childView]-100-|", options: nil, metrics: nil, views: ["childView": label]))
}

}

这是CollectionView定义:

    collectionView = ({
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 1
        layout.estimatedItemSize = CGSize(width: 300, height: 300)

        let view = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

        view.dataSource = self
        view.delegate = self


        view.registerClass(FooFoo.self, forCellWithReuseIdentifier: "Cell")

        view.backgroundColor = UIColor.clearColor()

        self.view.addSubview(view)

        return view
    })()

这是dataSource

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return items.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! FooFoo
    cell.text = "FooBar: \(indexPath.item)"
    return cell
}

我获取其他项目后,我尝试插入新的索引数组,或重新加载数据,结果是相同的 - 破坏的布局。

我也尝试用estimatedItemSize替换itemSize并且它确实工作得很好,所以我很确定它是因为自我调整大小。

结果如下:

Insert bathc of items on Fetch breaks layout

0 个答案:

没有答案