ios - UICollectionViewCell 布局问题 iOS9

标签 ios uicollectionview uicollectionviewcell ios9 xcode7

自从我迁移到新的 iOS9 和 Xcode 7 后,我偶然发现我的应用程序中的一个 UICollectionView 有问题。

显然,UICollectionView 似乎没有正确更新 UICollectionViewCell 布局和约束,直到它被重新使用。

图片胜于 Eloquent ——这是第一次看到 UIViewController 时的样子: enter image description here

然而,这不是正确的布局,当我向左水平滑动 UICollectionView 时,我很容易得到新出现的单元格的正确布局: enter image description here

当我向后滑动时,不正确的旧单元格现在被重新使用并且看起来不错。

现在,就像升级到 iOS9 和 Xcode 7 之前一样,我想要的效果是单元格即使在第一次出现时也具有正确的布局。

为方便起见,这里有更多关于 UICollectionView 的设置方式及其在 XIB 中的限制的详细信息: enter image description here

在代码中,它是非常标准的:

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 取而代之: enter image description here

最佳答案

解决这个问题:

  1. 使用 Nib(.xib) 文件创建您的自定义 UICollectionViewCell。

  2. 在您的自定义 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/

相关文章:

ios 知道 hls 直播何时播放完最后一 block

ios - 在 iOS 上使用 Corona 时,我可以将我的游戏信息分成两个数据库吗?

ios - 带有 Collection View 的自定义菜单栏

ios - 点击时更改和保持 UICollectionView 单元格大小

ios - UICollectionViewCell subview 的大小不正确

objective-c - 应用程序上的捆绑资源未更新。

ios - 创建 UIImage 数组

swift - 在按钮操作不起作用时动态更改 Collection View 单元格背景颜色

ios - 多行的 UICollectionView

ios - 在非滚动 UICollectionView 中动态调整 UICollectionViewCell 的大小