【问题标题】:Get UISwitch state into UIcollectionView at indexPath在 indexPath 处获取 UISwitch 状态到 UIcollectionView
【发布时间】: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


【解决方案1】:

编辑: 正如@Daniel 所说:https://stackoverflow.com/a/32587078/8162027 似乎没有为 UISwitch 制定协议和委托方法。 我成功地使用了这样的闭包: 在我的牢房里:

var mySwitchAction : (()->())?
@objc func switchValueChanged(_ sender: UISwitch) {
    self.switchAction?()
}
mySwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)

在我的 CollectionView 中:

cell.switchAction = {
        () in
        print("it works")
    }

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2013-04-05
    相关资源
    最近更新 更多