【发布时间】:2019-11-29 15:54:11
【问题描述】:
我通过 UICollectionView 显示用户列表(存储在 CoreData 中) 每个单元格有: - 名称(UItextField) - 一个状态 (ON/OFF) (bool)
我想通过 UISwitch 传递关于用户状态(ON 或 OFF)的布尔变量。
我已经正确设置了我的 collectionview func : 识别我的单元格,显示用户名,为 UISwitch 添加一个目标函数。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userId, for: indexPath) as! UserCell
let nameInfos = usersList[indexPath.item]
cell.usersList = nameInfos
nameInfos.name = cell.userNameTextField.text
cell.userNameTextField.delegate = self
let switchActive = cell.userSwitch
switchActive.addTarget(self, action: #selector(self.didPlayerActivate(_:)), for: .valueChanged)
return cell
}
@objc func didPlayerActivate(_ sender : UISwitch){
sender.isOn ? isActive() : isntActive()
}
// then my 2 func : isActive and isntActive
我的问题是如何使用我的“didPlayerActivate”函数将每个用户设置为开启或关闭。 我想过用 UISwitch 选择正确的 indexPath,但我不知道该怎么做。
【问题讨论】:
-
这里是按钮而不是开关stackoverflow.com/q/28659845/1630618的相同问题
-
尤其是Paulw11’s answer 是一种简洁的处理方式。
-
谢谢@vacawama,我想到了我以前见过的这个解决方案。但是,目前,它只是让我的应用程序崩溃:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: [MyApp.MySwitch _layoutAttributes]: unrecognized selector sent to instance 0x7fc6b1ebba00' -
委托方法似乎是一个很好的解决方案,但仍然无法达到 indexPath :每次我尝试让我的 indexPath 守卫时,它都会崩溃,即使我返回 nil...
-
最后,我使用了闭包,效果很好!协议/委托不是为 UISwitch 制定的。无论如何@vacawama,谢谢你的帮助。
标签: swift uicollectionviewcell uiswitch