2016-02-18 95 views
1

嗨我有兩個數組,只有一個數組更新與搜索欄..我保持TitleArray顯示在tableView標題和detailsArray顯示在tableView副標題..一旦我開始搜索只有我的打字後標題但字幕沒有任何改變。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 
     } 
    } 
} 


*/ 
+0

哪裏是在篩選結果的詳細信息的文本 –

+0

你想看到的'detailTextLabel'或不 –

+0

嗨,在detailTextLabel但它已經顯示出詳細的文字在搜索時不更新。希望你得到了我的觀點 –

回答

1

代替使用兩個單獨的陣列中只使用一個陣列,並用含有您使用填充的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) 
       } 

含過濾你的標題陣列地址。您的標題數組和過濾數組都包含相同的數據,您可以在第一次引用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! 
} 
+0

應該我添加新的地址類的swift文件?因爲我做了,並顯示錯誤與我的NS數據parseJSOn函數 –

+0

是創建一個新的swift文件,並添加上述代碼 –

+0

我做了它,並有一些變化,只有一個錯誤更新搜索結果:let array =(self.TitleArray as NSArray).filteredArrayUsingPredicate(searchPredicate)不能隱藏類型爲[Address]的值以強制鍵入NSArray –

0

你需要改變你的方法過濾數據,這樣,而不是僅僅適用謂詞時,明確地迭代並檢查謂詞的方式,如果你找到一個匹配,那麼你把這個項目和相應的描述到您的過濾的數組。

是這樣的:

func updateSearchResultsForSearchController(searchController: UISearchController) { 

    self.filteredNamesArray.removeAll(keepCapacity: false) 
    self.filteredDetailsArray.removeAll(keepCapacity: false) 

    let searchString = searchController.searchBar.text! 
    var index = 0 

    for title in self.TitleArray 
     if title.rangeOfString(searchString).location != NSNotFound { 
      self.filteredNamesArray.append(title) 
      self.filteredDetailsArray.append(self.DetailsArray[index]) 
     } 

     index += 1 
    } 

    self.AirportsTableView.reloadData() 
} 
+0

嗨,我把它和改變一點點因爲它表明我錯誤,但仍然顯示我(值範圍,索引。''沒有成員的位置' –