【问题标题】:How to use a UISwitch to add and remove data from an Array of Data如何使用 UISwitch 从数据数组中添加和删除数据
【发布时间】:2021-02-25 13:11:44
【问题描述】:

我在每个单元格中都有一个带有 UISwitch 的 tableview。我想要做的是,每当 UISwitch 打开时,它都会将该单元格添加到一个数组中,并且当开关关闭时它会删除它。现在只添加不删除。

一旦完成,我需要此 ViewController 中的 CollectionView 来更新并根据该数组中的数字直观地显示 newStringArray 单元格,并且还能够根据切换 UISwitch 的单元格出现和消失开。

import UIKit
class NewMoveViewController: UIViewController {
    private var stringSource = ["String 1,", "String 2", "String 3"]
    var newStringArray = Array<String>()
    private let tableView: UITableView = {
       let tableView = UITableView()
        tableView.rowHeight = 100
        return tableView
    }()
    private var collectionView: UICollectionView?
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView) 
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 50, height: 50)
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView?.register(NewMoveCollectionViewCell.self, forCellWithReuseIdentifier: NewMoveCollectionViewCell.identifier)
        collectionView?.showsHorizontalScrollIndicator = false 
        title = "Add to Group"
        tableView.register(NewMoveTableViewCell.self, forCellReuseIdentifier: NewMoveTableViewCell.identifier)
        tableView.delegate = self
        tableView.dataSource = self
        collectionView?.backgroundColor = .systemBlue
        collectionView?.dataSource = self
        collectionView?.delegate = self
        guard let myCollection = collectionView else {
            return
        }
        view.addSubview(myCollection)
        // Do any additional setup after loading the view.
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        collectionView?.frame = CGRect(x: 0, y: 100, width: view.frame.size.width, height: 50)
        tableView.frame = CGRect(x: 0, y: 200, width: view.frame.size.width, height: view.frame.size.height)
    }    
}

extension NewMoveViewController : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NewMoveTableViewCell.identifier, for: indexPath) as! NewMoveTableViewCell
        let switchView = UISwitch(frame: .zero)
        switchView.setOn(false, animated: true)
        switchView.tag = indexPath.row
        switchView.addTarget(self, action: #selector(self.switchDidChange(_:)), for: .valueChanged)
        cell.accessoryView = switchView       
        cell.configure(with: "", label: "test")        
        return cell
    }
    @objc func switchDidChange(_ sender: UISwitch) {        
        newStringArray.append(stringSource[sender.tag])
      //  newStringArray.remove(stringSource.remove(at: [s]))
       print(newStringArray)
    }    
    func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        return false
    }    
}

extension NewMoveViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return newStringArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NewMoveCollectionViewCell.identifier, for: indexPath) as! NewMoveCollectionViewCell
        return cell
    }
}

【问题讨论】:

    标签: swift xcode uitableview swift5 uiswitch


    【解决方案1】:

    为了获得您想要的更改,您必须设置属性来指示开关是打开还是关闭

    类似:var switchIsActive = false

    只需在功能中更改它,如果它打开,您执行一项操作,当它关闭时,您执行另一项操作。同样在函数之后你必须重新加载你的 tableView tableView.reloadData()

    您可以通过调用 Array.remove(at: Int) 来删除数组中的元素。可以通过单元格[indexPath.row]来完成

    【讨论】:

      【解决方案2】:

      最难的部分是从数组中删除一个对象,我在这些情况下的方法是将我的数组转换为 NSMutableArray,因为它具有删除特定对象的功能,然后在通知 viewController 的单元格中创建一个委托从列表中删除对象并重新加载 tableView。

      委托将是这样的:

      protocol RemoveObjectFromCell {
      func removeObjectIncell(object: MyObject)
      }
      
      class myCell: UITableViewCell {
      //your outlets and variables
      var object: MyObject? 
      var delegate: removeObjectIncell?
      
      
      func setupCell(object: myObject) {
      //configure your cell with the specific object
      }
      
      }
      

      确保在你的单元格类中调用 switch 操作的委托,如下所示:

      @IBAction func switchPressed(sender: UISwitch) {
          if !sender.isOn {
              self.delegate?.removeObjectIncell(object: self.object)
          }
      

      在视图控制器中实现您的协议并使用所需的功能,如下所示:

      class myViewController: UIViewController, RemoveObjectFromCell {
      
      //everything that goes in your class
      
      
          func removeObjectIncell(object: MyObject) {
          self.myArray.remove(object)
              DispatchQueue.main.async {
                  self.myTableView.reloadData()
              }
          }
      }
      

      【讨论】:

      • 非常感谢您对此的反馈!只是为了确保我正确理解(iOS 开发的新手)协议中的“MyObject”是否是 NSMutableArray?
      • 在 NSmutableArray 中,您可以附加任何对象,但要访问您必须强制转换它。例如:如果让 myobject = (myArray[0] as?String) { }。 NSMutableArray 不会推断数组的内容。
      猜你喜欢
      • 2017-01-22
      • 1970-01-01
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 2017-06-07
      • 2020-08-08
      • 1970-01-01
      相关资源
      最近更新 更多