在 indexPath 获取 UISwitch 状态到 UIcollectionView
Get UISwitch state into UIcollectionView at indexPath
我通过 UICollectionView(存储在 CoreData 中)显示用户列表
每个单元格都有:
- 一个名字(UItextField)
- 一个状态(开/关)(bool)
我想通过 UISwitch 传递关于用户状态(ON 或 OFF)的布尔变量。
我已经正确设置了我的 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,但我不知道该怎么做。
编辑:
似乎协议和委托方法不是为 UISwitch 制定的,正如@Daniel 所说:。
我成功地使用了这样的闭包:
在我的手机里:
var mySwitchAction : (()->())?
@objc func switchValueChanged(_ sender: UISwitch) {
self.switchAction?()
}
mySwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
在我的 CollectionView 中:
cell.switchAction = {
() in
print("it works")
}
我通过 UICollectionView(存储在 CoreData 中)显示用户列表 每个单元格都有: - 一个名字(UItextField) - 一个状态(开/关)(bool)
我想通过 UISwitch 传递关于用户状态(ON 或 OFF)的布尔变量。
我已经正确设置了我的 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,但我不知道该怎么做。
编辑:
似乎协议和委托方法不是为 UISwitch 制定的,正如@Daniel 所说:
var mySwitchAction : (()->())?
@objc func switchValueChanged(_ sender: UISwitch) {
self.switchAction?()
}
mySwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
在我的 CollectionView 中:
cell.switchAction = {
() in
print("it works")
}