基于UIView创建UICollectionViewCell



我正在尝试一个UICollectionView,它将不同的UIView作为单元格。这可能吗?还是我必须让它们成为UICollectionViewCells?

我没有objective-c示例,但您应该能够从下面的代码示例中获得概念。

一个如何创建一个包装UIView并更可重复使用的单元格的示例

class ProfileView: UIView {
var imageView: UIImageView!
var name: UILabel!
}
class ProfileCollectionViewCell: UICollectionViewCell {
let profileView = ProfileView() 
init() {
super.init()
configureConstraints()
}
func configureConstraints() {
// use a handy extension you've already built
contentView.addSubView(profileView)
profileView.pinToEdges(of: contentView)
}
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let row = self.objects[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "someId" for: indexPath) as? ProfileCollectionViewCell
cell?.profileView.imageView.image = row["image"]
cell?.profileView.name.text = row["name"]
return cell
}

注意:您可能需要管理"重置单元格状态",然后再使用类似的东西

override prepareForReuse() {
super.prepareForReuse() 
profileView.imageView.image = nil
profileView.name.text = ""
} 

您必须返回UICollectionViewCells。UICollectionView不接受UIViews。

您可以创建一个通用的UICollectionViewCell,它可以嵌入任何UIView。原因是集合视图单元格具有特定的布局和回收组合。

此外,您在UIView中直接在视图本身上添加子项,集合视图单元格具有contentView,如UITableViewCell