我在搜索MPMediaItems时遇到了一些问题。下面的代码将显示视图和过滤结果。取消搜索时不会清除结果(后续搜索仅向已经过滤的数据添加标准),在删除文本时更改结果(退格),或滚动到屏幕上最初显示的单元格之外。如何纠正此问题以获得前面提到的缺失行为?我尝试了各种各样的东西,包括将filteredTableData和pred设置为nil,但我显然在这里缺少一些重要的东西。任何帮助表示赞赏。提前谢谢......
class SongsViewController: UIViewController, UISearchResultsUpdating {
@IBOutlet var songsTableView: UITableView!
var tableData = MPMediaQuery.songsQuery()
var song : MPMediaItem?
var tableDataToFilter = MPMediaQuery.songsQuery()
var filteredTableData : MPMediaItemCollection?
var resultSearchController : UISearchController!
var pred : MPMediaPropertyPredicate?
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "SongCell", bundle: nil)
songsTableView.registerNib(nib, forCellReuseIdentifier: "cell")
resultSearchController = UISearchController(searchResultsController: nil)
resultSearchController.searchResultsUpdater = self
resultSearchController.dimsBackgroundDuringPresentation = true
resultSearchController.searchBar.sizeToFit()
songsTableView.tableHeaderView = self.resultSearchController.searchBar
songsTableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if resultSearchController.active {
let count = filteredTableData!.count
return count
} else {
if let collection = tableData.collections {
let collectionCount = collection.count
return collection.count
}
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : SongCell = self.songsTableView.dequeueReusableCellWithIdentifier("cell") as! SongCell
if resultSearchController.active {
song = filteredTableData!.items[indexPath.row]
let songName = song!.valueForProperty(MPMediaItemPropertyTitle) as! NSString
cell.songTitleLabel.text = songName as String
} else {
song = tableData.items![indexPath.row]
if song!.valueForProperty(MPMediaItemPropertyTitle) == nil {
cell.songTitleLabel.text = "Song Title is Blank" as String
} else {
let songName = song!.valueForProperty(MPMediaItemPropertyTitle) as! NSString
cell.songTitleLabel.text = songName as String
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
pred = MPMediaPropertyPredicate(value: searchController.searchBar.text!, forProperty: MPMediaItemPropertyTitle, comparisonType: MPMediaPredicateComparison.Contains)
tableDataToFilter.addFilterPredicate(pred!)
filteredTableData = MPMediaItemCollection(items: tableDataToFilter.items!)
self.songsTableView.reloadData()
}