gpt4 book ai didi

ios - 在 UICollectionViewCell 中带有参数的 Swift UICollectionViewController

转载 作者:行者123 更新时间:2023-11-29 13:52:32 25 4
gpt4 key购买 nike

我正在这样配置我的手机:

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
}

然后在我的单元格中,我有另一个具有某些属性的 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)
....
}
}

问题是当我初始化单元格时,它们是使用默认索引创建的,因此 anotherCollectionViewController 也有一个默认索引。如何让它“等待”我的索引?

最佳答案

您可以使用didSet 函数来初始化内部 View 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()
}
}

关于ios - 在 UICollectionViewCell 中带有参数的 Swift UICollectionViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58944181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com