【发布时间】:2017-08-03 04:48:48
【问题描述】:
我是 swift 新手,我正在尝试制作一个特定的子视图,它是通过调用父 collectioncell 中的函数选择的 collectionViewcell。
我正在调用setChosenToBeTrue(),它在子视图中将 isChosen 变量设置为 true,但由于某些奇怪的原因,变量的值并没有真正设置?可能是什么问题?谢谢!我查看了一些通过故事板传递数据的资源,或者有一些旧的资源没有快速运行,我仍然感到困惑。
这是我的代码
在父collectioncell,
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let rightCell = collectionView.dequeueReusableCell(withReuseIdentifier: rightCell, for: indexPath) as! RightCell
rightCell.setChosenToBeTrue()
return rightCell
}
在子视图中
var isChosen: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
func setChosenToBeTrue() {
self.isChosen = true //function is called but setting it here,
//when it reaches setUpViews(), this boolean is still false
}
func setupViews(){
self.isChosen = true // setting it here works (obviously)
print(isChosen)
backgroundColor = UIColor.gray
}
【问题讨论】:
-
您在 CellforRowAt 中调用了 setChosenToBeTrue,您是否在执行后使用断点进行了检查。 setChosenToBeTrue() 你的 setUpViews() 被调用了吗?如果没有,只需在 setChosenToBeTrue() 结束时调用 setUpViews()
-
使用断点首先调用 setChosenToBeTrue,然后调用 setupViews。我不想通过在 setChosenToBeTrue() 之后调用 setupViews 来破解我的解决方案,因为我并不总是将单元格设置为 true,只有选定的单元格
-
@xcalysta 由于您正在重用您的单元实例,请确保在您的
UICollectionViewCell子类中覆盖prepareForReuse(),以便您可以先进行清理并准备再次正确配置它。跨度>