如何使用多种功能填充搜索栏和表视图



>我有一个搜索栏和一个表格视图,我想把歌曲、艺术家和专辑的名字放进去。每当我在搜索栏中输入时,它只会过滤专辑名称,而不是歌曲或艺术家。我如何让它们都显示,因为只有 getAlbumName(( 出现?我刚刚添加了搜索.swift。

var search = [Search]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:  indexPath)

if (searchActive) {
cell.textLabel?.text = search[indexPath.row].getCleanName()
cell.textLabel?.text = search[indexPath.row].getArtistId()
cell.textLabel?.text = search[indexPath.row].getAlbumName()
} else {
searchActive = false
}
return cell;
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
search = search.filter({ (songName) -> Bool in
return songName.songname.lowercased().range(of: searchText.lowercased()) != nil
})
if(search.count == 0) {
searchActive = false;
} else {
searchActive = true;
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}

搜索.swift

class Search {
var search: Search!
var id = Int()
var name = String()
var cleanName = String()
var artist = String()
var album = String()

init?(id:String, name:String, artist:String, album:String) {
self.id = Int(id)!
self.name = name
self.cleanName = name.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: ".wav", with: "")
self.artist = artist
self.album = album
}
func getId() -> Int {
return id
}

func getName() -> String {
return name
}
func getCleanName() -> String {
return cleanName
}
func getArtistId() -> String {
return artist
}

func getAlbumName() -> String {
return album
}
}

如果要搜索多个属性,则必须为每个属性添加range(of表达式

search = search.filter({ song -> Bool in
return song.cleanName.range(of: searchText, options: .caseInsensitive) != nil ||
song.artist.range(of: searchText, options: .caseInsensitive) != nil ||
song.album.range(of: searchText, options: .caseInsensitive) != nil
})

考虑到search = search.filter实际上没有意义,因为您用过滤结果覆盖数组,如果您点击退格键,您将获得意外行为。

而且类中的大部分代码都是多余的。访问属性的方法毫无意义。它可以减少到

class Search {
let id : Int
let name, cleanName, artist, album : String

init(id: String, name: String, artist: String, album: String) {
self.id = Int(id)!
self.name = name
self.cleanName = name.replacingOccurrences(of: "_", with: " ").replacingOccurrences(of: ".wav", with: "")
self.artist = artist
self.album = album
}   
}

您可以使用song.album轻松获取相册

相关内容

  • 没有找到相关文章

最新更新