我有 FeedCell.swift 和 FeedCell.xib,在 feedcell xib 中,我将单元格自定义类设置为 'FeedCell'
视图控制器视图中的代码DidLoad
collectionView.register(UINib(nibName: "FeedCell", bundle: .main), forCellWithReuseIdentifier: "feedCell")
问题:
我想对 FeedCell 进行子类化,并将该类与 collectionView 一起使用喜欢:
class FeedCell:UICollectionViewCell {
@IBOutlet weak var showImageView: UIImageView!
@IBOutlet weak var showIconImageView: UIImageView!
}
class AppFeedCell: FeedCell {
override func awakeFromNib() {
super.awakeFromNib()
// configure cell
}
}
如何注册/使用 FeedCell 和 AppFeedCell with collectionview?
如果您的AppFeedCell具有不同的UI配置,例如,它不绑定FeedCell中定义的某些IBOutlet,或者它添加了超类中不存在的新I,那么您必须注册两个Nib(假设您有两个单独的Nib文件(
collectionView.register(UINib(nibName: "FeedCell", bundle: .main), forCellWithReuseIdentifier: "feedCell")
collectionView.register(UINib(nibName: "AppFeedCell", bundle: .main), forCellWithReuseIdentifier: "appFeedCell")
然后,您将能够在需要时取消每个队列。
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if you_need_AppFeedCell {
let cell : AppFeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("appFeedCell", forIndexPath: indexPath) as! AppFeedCell
return cell
} else
let cell : FeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as! FeedCell
return cell
}
}
这样,您可能有两个不同的笔尖文件,即使AppFeedCell子类FeedCell也是如此。
否则,如果类和子类共享相同的单元布局和出口,那么只需将取消排队的单元(FeedCell(转换为AppFeedCell就足够了,而无需注册另一个笔尖,正如Taras Chernyshenko上面指出的那样。
您无需为 AppFeedCell 注册单独的 xib。您已经将笔尖注册到您的收藏视图。
只需取消单元格排队并将其投射到cellForItemAtIndexPath
中所需的类即可。
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath
indexPath: NSIndexPath) -> UICollectionViewCell {
if you_need_AppFeedCell {
let cell : AppFeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as! AppFeedCell
return cell
} else
let cell : FeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("feedCell", forIndexPath: indexPath) as! FeedCell
return cell
}
}
您的AppFeedCell
将继承FeedCell
的所有网点,因此它也应该可以工作。
在单元格 xib/情节提要中,转到身份检查器集类:AppFeedCell
现在,在集合视图的数据源方法中,您可以创建类型为AppFeedCell的单元格。
试试这个。
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : AppFeedCell = collectionView.dequeueReusableCellWithReuseIdentifier("your_reusable_identifier", forIndexPath: indexPath) as! AppFeedCell
return cell
}