【发布时间】:2016-11-14 12:02:11
【问题描述】:
我想在练习字典中搜索名称键,然后在表格视图中显示过滤后的结果。我正在使用这个功能
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
let filtered = exercises.filter { $0["name"] == searchText }
print(filtered)
if(filtered.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.exercisesTableView.reloadData()
}
变量:
var exercises = [Exercise]()
var filtered: [NSMutableArray] = []
var searchActive: Bool = false
在搜索功能中出现错误
Type'Exercise' 没有下标成员
然后我遇到的问题是结果是 NSMutableArray,因此我无法将结果名称设置为要显示的单元格文本
无法强制将“NSMutableArray”类型的值转换为“String”类型
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if (searchActive){
cell.textLabel?.text = filtered[indexPath.row] as String
} else {
let exercise = exercises[indexPath.row]
cell.textLabel!.text = exercise.name
}
return cell
}
这是我的练习词典供参考:
final public class Exercise {
var id: Int
var descrip: String
var name: String
var muscles: [Int]
var equipment: [Int]
public init?(dictionary: [String: Any]) {
guard
let id = dictionary["id"] as? Int,
let descrip = dictionary["description"] as? String,
let name = dictionary["name"] as? String,
let muscles = dictionary["muscles"] as? [Int],
let equipment = dictionary["equipment"] as? [Int]
else { return nil }
self.id = id
self.descrip = descrip
self.name = name
self.muscles = muscles
self.equipment = equipment
}
我可以通过设置 var filters: [String] = [] 来修复第二个错误,这样它就可以用作单元格标题,但这并不能解决第一个错误,而且我不确定这样做是否正确?
【问题讨论】:
标签: swift uitableview uisearchbar