致命错误:当使用搜索栏Swift 3时索引超出范围

时间:2017-03-01 12:03:54

标签: ios swift xcode

尝试在表格视图上配置搜索栏时,我遇到了一些问题。我在表视图中的数据加载正常,如果我做出选择,则使用正确的信息进入下一个屏幕。但是在“表视图”屏幕上,只要在搜索栏中键入字母,应用程序就会因索引超出范围错误而崩溃。

它有点奇怪,因为之前我已将此配置为集合视图,并且搜索栏工作正常。

这是我的代码:

import UIKit
import GoogleMaps

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!

var TR: Tracks!
var track = [Tracks]()
var filteredTrack = [Tracks]()
var inSearchMode = false

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    tableView.delegate = self
    searchBar.delegate = self
    searchBar.returnKeyType = UIReturnKeyType.done  

    parseTrackCSV()
}

func parseTrackCSV() {

    let path = Bundle.main.path(forResource: "tracks", ofType: "csv")!

    do {
        let csv = try CSV(contentsOfURL: path)
        let rows = csv.rows

        for row in  rows {
            let trackId = Int(row["id"]!)!
            let name = row["name"]!
            let postcode = row["postcode"]!
            let trackType = row["type"]!
            let locID = row["locID"]!
            let lon = Double(row["long"]!)!
            let lat = Double(row["lat"]!)!
            let tr = Tracks(name: name, trackId: trackId, postcode: postcode, trackType: trackType, locId: locID, lon: lon, lat: lat)
            track.append(tr)

            }
        } catch let err as NSError {
        print(err.debugDescription)
    }
}
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return track.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "TrackCell", for: indexPath) as? TrackCell {
        let tr: Tracks!
        if inSearchMode {
            tr = filteredTrack[indexPath.row]
            cell.configureCell(track: tr)
        } else {
            tr = track[indexPath.row]
            cell.configureCell(track: tr)
        }
        cell.configureCell(track: tr)
        return cell
    } else {
        return UITableViewCell()
    }
}


func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    view.endEditing(true)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == "" {
        inSearchMode = false
        tableView.reloadData()
        view.endEditing(true)
    } else {
        inSearchMode = true
        let lower = searchBar.text!
        filteredTrack = track.filter({$0.name.range(of: lower) != nil})
        tableView.reloadData()

     }
  }


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var tr: Tracks!
    if inSearchMode {
        tr = filteredTrack[indexPath.row]
    } else {
        tr = track[indexPath.row]
    }
    performSegue(withIdentifier: "TrackDetailVC", sender: tr)
}

   override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "TrackDetailVC" {
        if let detailsVC = segue.destination as? TrackDetailVC {
            if let tr = sender as? Tracks {
                detailsVC.track = tr
            }
        }
    }
}
}

中断发生的行是:

 tr = filteredTrack[indexPath.row]

1 个答案:

答案 0 :(得分:6)

您正在使用track.count分配行数,并在启用搜索时尝试从filteredTrack获取值。很明显你必须得到同样的错误。 你需要在这里设置条件

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   if inSearchMode {
     return filteredTrack.count
  } else {
     return track.count
  }

}