【问题标题】:while select deselect row on didselectrow at indexPath getting crash而在 indexPath 的 didselectrow 上选择取消选择行时会崩溃
【发布时间】:2019-09-11 07:33:22
【问题描述】:

我正在创建我的第一个 Swift 应用程序,我正在将 JOSN 数据填充到 UITableview 并使用 struct 模型让我向您展示我填充 JSON 数据的代码

这是我的结构模型

struct QuotationListModel{
    var id: String
    var quantity: String
    var margin: String
    var created_date: String
    var part_number: String
    var total_price: String
    var freight: String
    var fk_customer_id: String
}

在我的ViewController 中,我已经声明了如下所示的数组

var quotationData = [QuotationListModel]()
var arrSelectedIds = [String]()

下面是我的 API 调用函数

func quotationListAPI(){
    let preferences = UserDefaults.standard
    let uid = "u_id"
    let acTkn = "acc_tkn"

    let u_ID = preferences.object(forKey: uid)
    let A_Token = preferences.object(forKey: acTkn)

    let params = ["user_id": u_ID!, "access_token": A_Token!]
    print(params)
    self.viewMainSpinner.isHidden = false
    self.viewInnerSpinner.startAnimating()
    Alamofire.request(quatationlist, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
        switch response.result{
        case.success(let value):
            let json  = JSON(value)
            print(json)
            let data = json["quation_list"]
            print(data)
            if data == []{
                self.viewMainSpinner.isHidden = true
                self.viewInnerSpinner.stopAnimating()
            }else{
                data.array?.forEach({ (qList) in
                    let q_list = QuotationListModel(id: qList["id"].stringValue, quantity: qList["quantity"].stringValue, margin: qList["margin"].stringValue, created_date: qList["created_date"].stringValue, part_number: qList["part_number"].stringValue, total_price: qList["total_price"].stringValue, freight: qList["freight"].stringValue, fk_customer_id: qList["fk_customer_id"].stringValue)
                    self.quotationData.append(q_list)
                })
                self.tblListView.reloadData()
                self.viewMainSpinner.isHidden = true
                self.viewInnerSpinner.stopAnimating()
            }
        case.failure(let error):
            print(error.localizedDescription)
            self.viewMainSpinner.isHidden = true
            self.viewInnerSpinner.stopAnimating()
        }

    })
}

所以我使用这个数组填充来自cellForRowAtIndexPath 的数据,直到现在每件事都对我来说很完美

但是在 didselect 上,当我取消选择已选中的行时,我会崩溃,这是我的 didSelect 代码

但是现在我想在“全选”按钮单击时选择所有表格视图的所有行,因此我使用了下面的代码,它对我来说工作正常,这是我的代码

@IBAction func btnSelectAllTapped(_ sender: UIButton) {
    if btnSelectAll.titleLabel?.text == "Select All"{
        self.btnSelectAll.setTitle("DeSelect All", for: .normal)
        self.btnSelectAll.backgroundColor = UIColor(red: 119/255, green: 119/255, blue: 119/255, alpha: 1)
        self.btnShare.isHidden = false
        self.arrSelectedIds = quotationSeelctedData.map({ (quotation: QuotationListModel) -> String in quotation.id })
        print(arrSelectedIds)
        self.tblListView.reloadData()
    }else{
        self.isSelectAll = false
        btnSelectAll.setTitle("Select All", for: .normal)
        btnSelectAll.backgroundColor = UIColor(red: 0/255, green: 175/255, blue: 239/255, alpha: 1)
        self.btnShare.isHidden = true
        self.arrSelectedIds.removeAll()
        print(arrSelectedIds)
        self.tblListView.reloadData()
    }
}

这是我的cellForRowAt indexPath代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! QuotationTableViewCell
    let id = quotationSeelctedData[indexPath.row].id
    if self.arrSelectedIds.contains(id){
        cell.viewMain.backgroundColor = UIColor(red: 210/255, green: 251/255, blue: 255/255, alpha: 1)
        cell.imgView.isHidden = false
    }else{
        cell.viewMain.backgroundColor = UIColor.white
        cell.imgView.isHidden = true
    }

    cell.lblPartNumber.text = quotationData[indexPath.row].part_number
    cell.llbQuantity.text = quotationData[indexPath.row].quantity
    cell.lblFreight.text = quotationData[indexPath.row].freight
    cell.lblMargin.text = quotationData[indexPath.row].margin
    cell.lblTotal.text = quotationData[indexPath.row].total_price
    cell.selectionStyle = .none
    return cell
}

所以选择所有功能都非常适合我

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(indexPath.row)
    let id = quotationSeelctedData[indexPath.row].id
    print(id)
    if arrSelectedIds.contains(id){
        self.arrSelectedIds.remove(at: indexPath.row)
        print(self.arrSelectedIds)
        if self.arrSelectedIds.count == 0{
            btnSelectAll.setTitle("Select All", for: .normal)
            btnSelectAll.backgroundColor = UIColor(red: 0/255, green: 175/255, blue: 239/255, alpha: 1)
            self.btnShare.isHidden = true
        }
        self.tblListView.reloadData()
    }else{
        self.arrSelectedIds.append(id)
        print(self.arrSelectedIds)
        self.btnSelectAll.setTitle("DeSelect All", for: .normal)
        self.btnSelectAll.backgroundColor = UIColor(red: 119/255, green: 119/255, blue: 119/255, alpha: 1)
        self.btnShare.isHidden = false
        self.tblListView.reloadData()
    }
}

所以请任何人帮我解决这个问题提前谢谢

【问题讨论】:

  • 发布你在崩溃时遇到的错误。
  • 你遇到了什么错误?

标签: ios arrays swift uitableview didselectrowatindexpath


【解决方案1】:

发生错误是因为您为选定的 id 使用了一个额外的数组,而不是在结构中添加了 isSelected 成员

索引路径不一定是项目的索引,因为id只是附加到数组中

替换

if arrSelectedIds.contains(id){
    self.arrSelectedIds.remove(at: indexPath.row)

if let index = arrSelectedIds.index(of: id){
    self.arrSelectedIds.remove(at: index)

尽管如此,还是删除 arrSelectedIds 并将成员 isSelected 添加到结构中。

【讨论】:

  • 我还有一个困惑,你能帮我解决一下吗
  • 请提出一个新问题并仅插入相关代码
  • 这不是一个难题,我只想将所有选定的数据存储到数组中,那么如何将所有选定的数据设置到数组中
  • 其实你的设计是个难题。如果您按照我的建议将 selected 信息放入结构中,您可以简单地 filter 数组 (.filter{$0.isSelected})。
  • stackoverflow.com/questions/57886054/… pelase 检查我提出了新问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
相关资源
最近更新 更多