为什么图像视图有时不会出现在集合视图单元格中?

bkw*_*ero 2 uiimageview uicollectionview swift swift3

我刚刚更新到 Swift 3。

在更新之前,我的集合视图运行良好。我做了推荐的更改以使编译器满意,但现在我遇到了这个问题。

我的自定义 UICollectionViewCells 中的图像视图根本不再出现。以编程方式生成的图像视图和原型图像视图都没有出现。

我已经给了图像视图背景颜色来检查我的图像是否为零。背景颜色没有出现,因此可以安全地假设图像视图根本没有出现。

细胞本身正在出现。每个图像视图下面都有一个标签,并且该标签使用正确的文本正确显示。

最令人困惑的部分是有时会出现图像视图,但似乎没有押韵或理由来说明为什么或何时出现。

我的代码非常标准,但无论如何我都会继续分享它:

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell: HomeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell

    cell.barLabel.text = searchClubs[indexPath.row].name
    cell.imageCell.image = searchClubs[indexPath.row].image

    cell.imageCell.layer.masksToBounds = true
    cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height / 2

    return cell

}

func feedSearchClubs(child: AnyObject) {

    let name = child.value(forKey: "Name") as! String    

    //Image
    let base64EncodedString = child.value(forKey: "Image")!
    let imageData = NSData(base64Encoded: base64EncodedString as! String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
    let image = UIImage(data:imageData! as Data)

    //Populate clubs array
    let club = Club.init(name: name, image: image!)
    self.searchClubs.append(club)

    DispatchQueue.main.async {
           self.collectionView.reloadData()
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

从 Xcode 8 开始,您必须调用 layoutIfNeeded() 来计算大小(在您的情况下,您需要知道 cell.imageCell.frame.height)和自动布局规则中的位置或使用cornerRadius 的固定值。

cell.imageCell.layoutIfNeeded()
cell.imageCell.layer.masksToBounds = true
cell.imageCell.layer.cornerRadius = cell.imageCell.frame.height / 2
Run Code Online (Sandbox Code Playgroud)

或者

cell.imageCell.layer.masksToBounds = true
cell.imageCell.layer.cornerRadius = 5
Run Code Online (Sandbox Code Playgroud)