我通过 UICollectionView 显示用户列表(存储在 CoreData 中) 每个单元格有: - 名称(UItextField) - 状态(开/关)( bool )
我想使用 UISwitch 传递有关用户状态(ON 或 OFF)的 bool 变量。
我已经正确设置了我的 CollectionView 函数: 识别了我的单元格,显示了用户名,为 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,但我不知道该怎么做。
最佳答案
编辑: 看来协议(protocol)和委托(delegate)方法不是为 UISwitch 设计的,正如@Daniel 所说:https://stackoverflow.com/a/32587078/8162027 。 我成功地使用了这样的闭包: 在我的牢房中:
var mySwitchAction : (()->())?
@objc func switchValueChanged(_ sender: UISwitch) {
self.switchAction?()
}
mySwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
在我的 CollectionView 中:
cell.switchAction = {
() in
print("it works")
}
关于swift - 将 UISwitch 状态获取到位于 indexPath 的 UIcollectionView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57133028/