我会假设 user1...user119 的类型是 User,而不是你可以这样做:
let collection: [Any] = [user1,...user60,"Yes",user61,user62....,user119,"Yes"]
for element in collection {
if let user = element as? User {
//do whatever you want with user class
} else let yesString = element as? String, yesString == "Yes" {
//you found "Yes" string
} else {
//unknown type
}
}
当你想使用 collectionView 数据源中的数据时,你可以使用相同的逻辑,从数组中获取元素并执行相同的操作来检查元素是 User 还是 String,值为 "Yes ”。
由于从问题中不清楚您是否需要集合的“是”元素,您可以先从数组中删除“是”元素,然后您将拥有一个数组[User]。
由于您的collectionView 将有两种类型的单元格:用户单元格和图像视图单元格,您必须先注册它们才能用于collectionView,例如:
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "userCellIdent")
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "yesCellIdent")
(如果您对每种类型都有自定义子类,大多数情况下您应该为您希望注册的每种细胞类型将UICollectionViewCell.self 替换为YourCollectionViewCellSubclassName.self)
在cellForItemAt 你这样做:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let element = collection[indexPath.item]
if let user = element as? User {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "userCellIdent", for: indexPath)
//configure your cell with user data
return cell
} else if let yesString = element as? String, yesString == "Yes" {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "yesCellIdent", for: indexPath)
//configure your with the image view when element in collection is "Yes"
return cell
} else {
//you have something other than user and "Yes" in the collection
fatalError()
}
}