如何使用 Swift 4 解决表视图数据数组"Out of range values"?



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

类似:

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中维护了两个按钮。第一个Add将显示,一旦用户点击添加按钮,它将调用JSON并获取ID值,之后只有ID值附加在cell.accessibilityValue = String(id[indexPath.row])中,然后我也会重新加载。

我面临的问题:

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

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

这是我的代码

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()
}

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

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

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

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

相关内容

最新更新