swift - 将 UISwitch 状态获取到位于 indexPath 的 UIcollectionView 中

标签 swift uicollectionviewcell uiswitch

我通过 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/

相关文章:

Swift:如何访问仅使用一个函数以编程方式创建的多个 UISwitch

swift - 滚动其中包含 TextFields 的列表时出现 NavigationBarTitle 问题

arrays - UserDefaults 数组连续返回 nil

ios - UICollectionViewCell - 如何选择 UIButton 操作方法中的所有项目/单元格

ios - 无法切换 UISwitch 的状态

android - 在 Android 中使用开关切换蓝牙

ios - 上传到 App Store,无法在代码设计对话框中单击 "Always Allow"

swift - macOS SwiftUI 表超过 10 列?

swift - 如何使用swift中的计数数组移动到下一个对象?

ios - 如何使用 slider 更改 UICollectionViewCell 的框架?