【问题标题】:Moving a tableview cell from one section to another but receiving an error将表格视图单元格从一个部分移动到另一个部分但收到错误
【发布时间】:2020-05-20 16:42:34
【问题描述】:

我有一个 tableview,我试图将一个单元格从一个部分移动到另一个部分。但是,当我尝试执行此操作时,我会在线收到'Fatal Error: Index out of range'goals[1].append(goals[0][indexPath.row])

这是我的代码。

import UIKit

class GoalsViewController: UIViewController {

@IBOutlet weak var goalTableView: UITableView!

let sections: [String] = ["Mark as Complete:", "History:"]
var goals: [[String]] = [] //This is like this because the cell is also transported from another table view in a separate view controller to this table view. 
let theEmptyModel: [String] = ["No data in this section."]
extension GoalsViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if goals.indices.contains(section) {
            return goals[section].count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TodayGoalViewCell_1", for: indexPath) as? GoalTableViewCell
            cell?.goalLabel.text = goals[indexPath.section][indexPath.row]
            cell?.cellDelegate = self
            cell?.index = indexPath
            return cell!
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section]
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            progressBarAnimation()

            if goals[0] != theEmptyModel {
                goals[1].append(goals[0][indexPath.row])
                if goals[1].first!.contains("No data in this section.") {
                    goals[1].removeFirst()
                }
                goals[0].remove(at: indexPath.row)
                if goals[0].count == 0 {
                    goals[0].append(contentsOf: theEmptyModel)
                }
                tableView.reloadData()
                }
            }

【问题讨论】:

    标签: ios swift xcode uitableview


    【解决方案1】:

    其中一些下标调用失败 goals[1]goals[0][indexPath.row] - 尝试调试或打印数组。为避免严重崩溃,请使用此扩展程序中的get()

    extension Array {
        func get(_ index: Int) -> Element? {
            if 0 <= index && index < count {
                return self[index]
            } else {
                return nil
            }
        }
    }
    

    在方法的开头使用guard 检查或if 语句。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多