如何使用单独的UITableViewDataSource类管理#selector?

问题描述 投票:0回答:1

我为UITableViewDataSourceUITableView有一个单独的类

import UIKit

class CardDataSource: NSObject, UITableViewDataSource {

    //MARK:- Property
    var medialObjects: [MediaCardObject]?
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    var viewController: AddNewVC?

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return medialObjects?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let obj = medialObjects![indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: "MediaTextTableViewCell") as! MediaTextTableViewCell

        cell.btnDelete.tag = indexPath.row
        cell.btnDelete.addTarget(self, action: #selector(AddNewVC.deleteItem(sender:)), for: .touchUpInside)
        cell.tfCardText.text = obj.path
        cell.tfCardText.tag = indexPath.row
        cell.tfCardText.returnKeyType = .done
        cell.tfCardText.delegate = viewController
        cell.selectionStyle = .none
        return cell
    }
}

数据在我的UITableView上很好地加载,但是问题是当我单击删除按钮时它崩溃了,并说

***由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[MediaCards.CardDataSourcedeleteItemWithSender:]:无法识别的选择器已发送到实例0x600003394cc0'

我也尝试过

cell.btnDelete.addTarget(self, action: #selector(viewController?.deleteItem(sender:)), for: .touchUpInside)

这里是AddNewVC中的删除方法>

//MARK:- Delete
@objc func deleteItem(sender: UIButton) {

    let selectedIndex = sender.tag
    deleteObjectIndexPath = IndexPath(row: selectedIndex, section: 0)
    confirmDelete()
}

并且在AddNewVC类中

var tblDataSource = CardDataSource()

override func viewDidLoad() {
    super.viewDidLoad()

    tblDataSource.viewController = self
    tblMediaCards.dataSource = tblDataSource

    if forEdit {
        let cards = mediaObject?.cards?.allObjects as! [MediaCard]
        for obj in cards {
            let mediaCardObj = MediaCardObject.init(type: obj.type ?? "", path: obj.path ?? "", index: Int(obj.index))
            self.medialObjects.append(mediaCardObj)
        }

        medialObjects = medialObjects.sorted(by: { $0.index! < $1.index! })
        tblDataSource.medialObjects = medialObjects

        self.tblMediaCards.reloadData()
    }
}

但是它仍然由于相同的原因而崩溃。尽管委托工作正常。

<<

目标错误:

ios swift uitableview nsobject unrecognized-selector
1个回答
0
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.