首页 > 解决方案 > 如何使用 Swift 4 解决 Tableview 数据数组“超出范围值”?

问题描述

我的场景我将多个数组用于多个单元格标签。我正在维护每个单元格两个不同的标签。我为单元标签分配了单独的数组。

喜欢:

cell.accessibilityValue = String(id[indexPath.row])
cell.name_Label.text = name[indexPath.row]
cell.city_Label.text = city[indexPath.row] 

在这里,我从 JSON 中获取并单独附加的所有数组值。我将只显示名称和城市,但 cell.accessibilityValue "ID" 我试图在其中存储该 ID,cell.accessibilityValue因为我在单元格ADDPlus. 首先添加将显示,一旦用户单击该添加按钮,它将调用 JSON 并获取 ID 值,之后只有 ID 值附加在其中,cell.accessibilityValue = String(id[indexPath.row])然后我也会重新加载。

我面临的问题:

  1. 最初没有值, cell.accessibilityValue = String(id[indexPath.row])所以我得到了超出范围的错误。
  2. 添加按钮后,我试图将 ID 值附加到 id 数组中,它应该分配到我的单元格中,因为单击添加后它将隐藏并显示加号按钮,对于加号按钮单击以获取该存储的 ID。

注意:这里的 ID 可能有机会为空,所以如果可用的值需要分配,否则为空。

这是我的代码

protocol CustomCellDelegate {
    func cellButtonTapped(cell: CustomOneCell)
}

class CustomOneCell: UITableViewCell {

    // Link those IBOutlets with the UILabels in your .XIB file
    @IBOutlet weak var name_Label: UILabel!
    @IBOutlet weak var city_Label: UILabel!
    @IBOutlet weak var add_Button: UIButton!

    var delegate: CustomCellDelegate?

    @IBAction func add_buttonTapped(_ sender: Any) {
        delegate?.cellButtonTapped(cell: self)
    }
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CustomCellDelegate {

    var id = [Int]()        // This is from JSON but Initially no values
    var name = [String]()   // This is from JSON ["Item 1", "Item2", "Item3", "Item4"]
    var city = [String]()   // This is from JSON ["Item 1", "Item2", "Item3", "Item4"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    //MARK - UITableview
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return name.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomOneCell

        cell.delegate = self
        cell.accessibilityValue = String(id[indexPath.row]) // #1. Initially no values, So I am getting out of range Error

        cell.name_Label.text = name[indexPath.row]
        cell.city_Label.text = city[indexPath.row]

        return cell
    }

    func cellButtonTapped(cell: CustomOneCell) {

        let url = URL(string: "")!
        var request = URLRequest(url: url)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data else {
                print("request failed \(error)")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
                    for item in json {

                        let id = item["id"]!
                        self.id.append(id as! Int) // #2. After table load I am appending some values into id array
                    }
                    //Table reload to assign id values
                }
            } catch let parseError {
                print("parsing error: \(parseError)")
                let responseString = String(data: data, encoding: .utf8)
                print("raw response: \(responseString!)")
            }
        }
        task.resume()

    }

标签: iosarraysjsonswifttableview

解决方案


最简单的方法是添加范围检查tableView:cellForRowAt

if indexPath.row < id.count {
    cell.accessibilityValue = String(id[indexPath.row])
}

但如果可能的话,我会考虑创建一个包含所有三个值的结构并维护一个而不是三个数组

struct SomeData {
    var id: Int
    var name: String
    var city: String
}

推荐阅读