[英]Swift UICollectionViewController with parameter inside UICollectionViewCell
I'm configuring my cell like this:我正在像这样配置我的单元格:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId for: indexPath) as! MyCollectionViewCell
cell.index = indices[indexPath.item]
return cell
}
And then inside my cell, I have another UICollectionViewController that has some property, say - index然后在我的单元格内,我有另一个 UICollectionViewController 有一些属性,比如说 - 索引
class MyCollectionViewCell: UICollectionViewCell {
var index: Int = 0
var myController = UINavigationController(rootViewController: anotherCollectionViewController(index: self.index ?? 0))
override init(frame: CGRect) {
super.init(frame: frame)
// setting constraints, adding views etc
addSubview(anotherCollectionViewController.view)
....
}
}
The issue is when I initialize cells, they are created with default index thus anotherCollectionViewController has a default index as well.问题是当我初始化单元格时,它们是使用默认索引创建的,因此 anotherCollectionViewController 也具有默认索引。 How do I make it 'wait' for my index?
如何让它“等待”我的索引?
Better give alternate name to one of them.最好给其中一个人提供替代名称。
You can use didSet
function to init inner view controller, didSet
is called immediately after the new value is stored:您可以使用
didSet
function 来初始化内部视图 controller,在存储新值后立即调用didSet
:
class MyCollectionViewCell: UICollectionViewCell {
var index: Int? {
didSet {
if let index = index {
myController = UINavigationController(rootViewController: anotherCollectionViewController(index: index))
}
}
}
var myController: UINavigationController? {
didSet {
// remove old view controller from hierarchy
// oldValue?.removeFromParent()
// setting constraints, adding views etc
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
index = nil
myController = nil
super.prepareForReuse()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.