代码之家  ›  专栏  ›  技术社区  ›  Max Kraev

如何在Swift中将开关状态绑定到对象?

  •  -1
  • Max Kraev  · 技术社区  · 8 年前

    在我的应用程序中,我有一个开关,我希望它能作为保存图像的指示器。现在我只有一个保存所有图像的按钮。

    enter image description here

    举个例子就更有意义了

    我所尝试的:

    func saveTapped() {
    
    let cell = collectionView?.cellForItem(at: indexPath) as! CustomCell
    
    for image in images where cell.savingSwitch.isOn  {
    
    ...
    

    但我无法访问indexPath。为了访问collectionView中的特定行,我应该如何调用这个Save方法?还是有其他方法?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Gereon    8 年前

    首先,您需要一种将“保存”设置存储在表中每个图像旁边的方法,例如,将图像和标志保存在结构中:

    struct TableEntry {
       let image: UIImage
       var save = false
    }
    

    并使用 var images: [TableEntry] 在tableview的数据源中。

    然后可以使用 tag 用于存储其所在行的每个UISwitch的属性,例如

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(...)
        cell.switch.tag = indexPath.row
        cell.switch.isOn = self.images[indexPath.row].save
        cell.imageView.image = self.images[indexPath.row].image
        return cell
    }
    

    然后在开关值更改时调用的方法中使用标记,以了解所引用的图像:

    @IBAction func switchChanged(_ sender: UISwitch) {
        self.images[sender.tag].save = sender.isOn
    }
    
    func saveTapped() {
        let imagesToSave = self.images.filter { $0.save }
    }
    
        2
  •  1
  •   Kamran    8 年前

    在您的 CustomCell ,可以添加要在以下情况下激发的闭包 switch 状态更改如下:,

    class CustomCell: UITableViewCell {
    
       var onSwitchStateChange: ((Bool) -> Void)?
    
       @IBAction func switchTapped(_ sender: UISwitch) {
           self.onSwitchStateChange?(sender.isOn)
       }
    }
    

    然后您可以更新 cellForRowAt 如下图所示,

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
       cell.onSwitchStateChange = { state in
         guard state else { return }
    
         let image = images[indexPath.row]
         // Upload Image
       }
    }