自从我迁移到新的 iOS9 和 Xcode 7 后,我偶然发现我的应用程序中的一个 UICollectionView
有问题。
显然,UICollectionView
似乎没有正确更新 UICollectionViewCell
布局和约束,直到它被重新使用。
图片胜于 Eloquent ——这是第一次看到 UIViewController
时的样子:
然而,这不是正确的布局,当我向左水平滑动 UICollectionView
时,我很容易得到新出现的单元格的正确布局:
当我向后滑动时,不正确的旧单元格现在被重新使用并且看起来不错。
现在,就像升级到 iOS9 和 Xcode 7 之前一样,我想要的效果是单元格即使在第一次出现时也具有正确的布局。
为方便起见,这里有更多关于 UICollectionView
的设置方式及其在 XIB 中的限制的详细信息:
在代码中,它是非常标准的:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : MatchmakersCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! MatchmakersCollectionViewCell
cell.imageView.backgroundColor = UIColor.lightGrayColor()
cell.bottomName.text = "StackOverflow"
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.matchmakers.count
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
每次更新数据源 (self.matchmakers) 时,我都会调用 self.collectionView.reloadData()
我注意到的最后一件事非常奇怪,当使用 Xcode 调试调试 View 层次结构时,UICollectionViewCell
从未正确显示 subview ,只是给了我一个默认的 UIView
取而代之:
最佳答案
解决这个问题:
使用 Nib(.xib) 文件创建您的自定义 UICollectionViewCell。
在您的自定义 UICollectionViewCell 中,覆盖 didMoveToSuperView() 方法以添加此
self.setNeedLayout()
self.layoutIfNeeded()
3.在你的 UIViewController viewDidLoad() 方法中
self.collectionView.registerNib(UINib(nibName: "yourNibName", bundle: nil), forCellWithReuseIdentifier: "Cell")
--------更新20150923
只需要第2步,重写didMoveToSuperView方法添加
self.setNeedLayout()
self.layoutIfNeeded()
在您的自定义 UICollectionViewCell 类中。
感谢@macayer
关于ios - UICollectionViewCell 布局问题 iOS9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32631053/