【问题标题】:How to delete the cell while clicking the delete button in mvvm如何在单击 mvvm 中的删除按钮时删除单元格
【发布时间】:2018-05-02 05:05:38
【问题描述】:

我已经在UITableview 中列出了数据。所以我得到了输出。输出是名称列表。

我已经在 mvvm 中完成了。现在我需要在单击删除按钮时删除单元格并需要更新 tableview。

我的模型视图:-

class ViewModel: NSObject {
    var datasourceModel:DataSourceModel

    init(withdatasource  newDatasourceModel: DataSourceModel) {
        datasourceModel = newDatasourceModel
    }

    func datafordisplay(atindex indexPath: IndexPath) -> Model{
        return  datasourceModel.dataListArray![indexPath.row]
    }

    func numberOfRowsInSection(section:Int) -> Int {
        return (datasourceModel.dataListArray?.count)!
    }
}

我的数据源模型类:-

class DataSourceModel: NSObject {
    var dataListArray:Array<Model>? = []

    init(array :Array<[String:Any]>?) {
        super.init()
        var newArray:Array<[String:Any]> = []
        if array == nil {
            newArray = self.getJsonDataStored22()
        }
        else {
            newArray = array!
        }

        var datalist:Array<Model> = []
        for dict in newArray {
            let model = Model(dictionary: dict)
            datalist.append(model!)
        }
        self.dataListArray = datalist
    }
}

typealias dummyDataSource22 =  DataSourceModel
extension dummyDataSource22 {
    func getJsonDataStored22() ->Array<Dictionary<String,String>>{
            let jsonArray = [["name":"Dosa Fest"],["name":"Organic Vegan Fest"],["name":"Food Of Life Time"],["name":"Tea Time"],["name":"Dosa Fest"],["name":"Organic Vegan Fest"],["name":"Food Of Life Time"],["name":"Tea Time"]] as Array<Dictionary<String,String>>
            return jsonArray
    }
}

还有我的 UIViewcontroller:-

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return chartViewModel.numberOfRowsInSection(section: section)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let identifier = "cell"
    var cell:ChartCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? ChartCell

    if cell == nil {
        tableView.register(UINib(nibName: "ChartCell", bundle: nil), forCellReuseIdentifier: identifier)
        cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? ChartCell
    }

    cell.setEventData(charts: chartViewModel.datafordisplay(atindex: indexPath))
    return cell
}

我的 UITableviewcell:-

 @IBOutlet weak var name: UILabel!

     override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func setEventData(charts:Model) {
        self.name.text = charts.restaurantname
    }

那么现在如何在单击删除按钮时执行删除方法。ModelViewviewController 中应添加的所有代码

【问题讨论】:

  • 如何在 mvvm 方法中删除单元格
  • 如果你使用 mvvm,你应该向你的 viewModel 发送像删除单元格这样的 ui 事件。 viewModel 改变自己并发送通知。然后 view(viewController) 响应它并更改 UI。
  • @SolaWing 怎么办
  • @SolaWing 应该在视图模型和视图控制器中编写什么函数
  • 任何人都可以解决问题

标签: ios swift uitableview mvvm


【解决方案1】:

通常情况下,在MVVM中,所有UI相关的逻辑都应该写在ViewModel中,View或者ViewController只需要根据ViewModel展示UI,并将UI Event发送给ViewModel即可。当 ViewModel 发生变化时,它会发送事件或通知,以便 View 可以响应和更改。这称为绑定。同样,viewModel 也应该绑定到 Model。

在你的情况下,ViewModel 应该有一个删除方法,像这样

func delete(atIndex indexPath: IndexPath) {
    // model should declare modify method and viewModel should call it and observe changes too. here directly modify it for simplicity
    // you may also need to check input parameter is valid

    // now input is valid, do the change
    datasourceModel.dataListArray!.remove(at: indexPath.row)
    // and then fire a notification
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "DeleteAtRow"), object: self, userInfo: ["indexPath" : indexPath])
}

因此视图可以将事件传递给它

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        // pass delete cell event to viewModel
        chartViewModel.delete(atIndex: indexPath)
    }
}

view也需要绑定修改

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    NotificationCenter.default.addObserver(self, selector: #selector(viewModelDeleteRows(n:)), name: NSNotification.Name(rawValue: "DeleteAtRow"), object: chartViewModel)
}

@objc func viewModelDeleteRows(n: NSNotification) {
    if let i = n.userInfo?["indexPath"] as? IndexPath {
        // respond to viewModel changes and sync UI
        self.tableView.deleteRows(at: [i], with: .automatic)
    }
}

此外,您可以将单元格删除事件传递给它的控制器,然后控制器可以传递给 viewModel

var deleteCell : ((ChartCell) -> Void)?
@IBAction func clickDeleteButton(sender: UIButton) {
    deleteCell?(self)
}

并配置单元格

cell.deleteCell = {[weak self] in
        if let i = self?.tableView.indexPath(for: $0) {
            self?.chartViewModel.delete(atIndex: i)
        }
}

【讨论】:

  • 这行得通....非常感谢....但是我在 tableviewcell 上有一个按钮。所以在点击删除按钮时它应该删除。所以应该做些什么改变
  • viewController可以给cell的按钮添加回调,当按钮点击时,可以找到indexPath并调用viewModel的方法。
  • 我已经在 tableviewcell 中给出了按钮插座。所以我需要在 tableviewcell 类中进行操作。如果是这样,怎么办
  • cell可以声明一个block为回调,然后在cell的button点击方法中调用block
  • 嗨,你能给出代码来调用单元格的点击方法上的块
猜你喜欢
  • 2021-12-13
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多