fatal index error ios

时间:2018-04-20 00:38:07

标签: ios swift xcode

Detail view

    @IBAction func datePickerChanged(_ sender: UIDatePicker) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM dd, YYYY"
    let somedateString = dateFormatter.string(from: sender.date)
    list1.append(somedateString)

}

Master View

public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cellIdentifier = "Cell"
    var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.value2, reuseIdentifier: cellIdentifier)
    }
    cell?.textLabel?.text = (list[indexPath.row] as! String)
    cell?.detailTextLabel?.text = list1[indexPath.row]
    return cell!
}

I have this code This throws me a fatal error: index out of range when I leave the detailTextLabel empty, I want to display the title content in my table view even though the detail label content is empty

image here

In this case, the date shouldn't be mandatory.

1 个答案:

答案 0 :(得分:2)

You can try to check the index before accessing the array element

public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cellIdentifier = "Cell"
    var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
    if cell == nil {
    cell = UITableViewCell(style: UITableViewCellStyle.value2, reuseIdentifier: cellIdentifier)
    }
    cell?.textLabel?.text = (list[indexPath.row] as! String)
    if(indexPath.row < list1.count) {
       cell?.detailTextLabel?.text = list1[indexPath.row]
    }
    else {
       // to clear dequeued content
       cell?.detailTextLabel?.text = ""
    }
    return cell!
}