gpt4 book ai didi

ios - 搜索时出现 TableView 错误

转载 作者:行者123 更新时间:2023-11-28 06:48:48 25 4
gpt4 key购买 nike

您好,我有两个数组,只有一个数组正在使用搜索栏更新。我保留 TitleArray 以显示在 tableView 标题中,而 detailsArray 则显示在 tableView 副标题中。一旦我在键入后开始仅搜索标题,但副标题没有任何变化.

@IBOutlet weak var AirportsTableView: UITableView!

var TitleArray = [String]()
var DetailsArray = [String]()

var NumberOfRows = 0


var filteredNamesArray = [String]()
var filteredDetailsArray = [String]()
var resultSearchController = UISearchController!()




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

// Do any additional setup after loading the view.


self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self

self.resultSearchController.dimsBackgroundDuringPresentation = false
self.resultSearchController.searchBar.sizeToFit()
self.resultSearchController.loadViewIfNeeded()

self.AirportsTableView.tableHeaderView = self.resultSearchController.searchBar

self.AirportsTableView.reloadData()


parseJSON()

}


func parseJSON() {

if let path = NSBundle.mainBundle().pathForResource("airports", ofType: "json") {
do {
let data = try NSData(contentsOfURL: NSURL(fileURLWithPath: path), options: NSDataReadingOptions.DataReadingMappedIfSafe)
let jsonObj = JSON(data: data)
if jsonObj != JSON.null {
// print("jsonData:\(jsonObj)")


NumberOfRows = jsonObj.count

for i in 0...NumberOfRows {

let City = jsonObj[i]["city"].string as String!
let Country = jsonObj[i]["country"].string as String!
let Iata = jsonObj[i]["iata"].string as String!
let Name = jsonObj[i]["name"].string as String!


self.TitleArray.append("\(City) - \(Country) - \(Iata)")
self.DetailsArray.append("\(Name)")

}


} else {
print("could not get json from file, make sure that file contains valid json.")
}
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("Invalid filename/path.")
}

}



override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/



// MARK: - Table view data source

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections

return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows


if self.resultSearchController.active

{
return self.filteredNamesArray.count

} else

{

return self.TitleArray.count
}
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell?


if self.resultSearchController.active
{
cell!.textLabel?.text = self.filteredNamesArray[indexPath.row]

} else
{
cell!.textLabel?.text = self.TitleArray[indexPath.row]
cell!.detailTextLabel?.text = self.DetailsArray[indexPath.row]
}


return cell!
}

func updateSearchResultsForSearchController(searchController: UISearchController) {

self.filteredNamesArray.removeAll(keepCapacity: false)

let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)

let array = (self.TitleArray as NSArray).filteredArrayUsingPredicate(searchPredicate)

self.filteredNamesArray = array as! [String]

self.AirportsTableView.reloadData()
}


// MARK: - Segues

/*

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "AirportDetails" {
if let indexPath = self.AirportsTableView.indexPathForSelectedRow {
let airportDetail : Airports = TitleArray[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! AllWaysFlightsViewController
controller.airportDetail = airportDetail
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}


*/

最佳答案

不要使用两个单独的数组,而是只使用一个数组,并用包含您用来填充 tableView 的两个变量的对象填充它。

class Address {
var city: String
var detail: String

init(city: String, detail:String) {
self.city = city
self.detail = detail
}
}

像这样解析你的 json:

for i in 0...NumberOfRows {

let City = jsonObj[i]["city"].string as String!
let Country = jsonObj[i]["country"].string as String!
let Iata = jsonObj[i]["iata"].string as String!
let Name = jsonObj[i]["name"].string as String!

let city = "\(City) - \(Country) - \(Iata)"

let address = Address(city: city, detail: Name)
self.TitleArray.append(address)
self.filteredNamesArray.append(address)
}

过滤包含地址的标题数组。您的 titlearray 和 filtered array 都包含第一次相同的数据,您可以为此引用 json 解析。在这里您可以使用一个进行过滤,当搜索栏为空时用户取消他的搜索您可以从另一个重新填充您的数组。

func updateSearchResultsForSearchController(searchController: UISearchController) {

self.filteredNamesArray.removeAll(keepCapacity: false)

let searchPredicate = NSPredicate(format: "SELF.city CONTAINS[c] %@", searchController.searchBar.text!)

let array = (self.TitleArray as NSArray).filteredArrayUsingPredicate(searchPredicate)

self.filteredNamesArray = array as! [Address]

self.AirportsTableView.reloadData()
}

您的 tableView 逻辑将相应更改

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows

return self.filteredNamesArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell?

let address = self.filteredNamesArray[indexPath.row]
cell!.textLabel?.text = address?.city
cell!.detailTextLabel?.text = address?.detail

return cell!
}

关于ios - 搜索时出现 TableView 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35480393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com