iOS - 将 tableView 中的 numberOfSections 设置为筛选单元格的数量 (Swift)
iOS - Set numberOfSections in tableView to number of filtered cells (Swift)
我已经设置了我的 tableView,因此它根据与 2 个用户输入(factor1UserInput 和 factor2UserInput)匹配的数组的每个子项(factor1 和 factor2)的 2 个因子的值进行过滤。问题是 - 因为我将我的 numberOfSections 设置为 return array.count - 它会为数组中的每个子项加载所有单元格,包括未填充的单元格。
因此,我试图将我的 tableView 中的 numberOfSections 设置为过滤单元格(我正在填充的单元格)的数量 - 除非有更好的方法来过滤这些单元格以便不加载未填充的单元格。
numberOfSections 代码:
func numberOfSections(in tableView: UITableView) -> Int {
return array.count
}
表格视图代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell", for: indexPath)
let preview = array[indexPath.section]
// BELOW LINE FILTERS THE DATA
if preview.factor1 == factor1UserInput && preview.factor2 == factor2UserInput {
// TRYING TO ONLY LOAD THESE CELLS
print("something matches the filter")
cell.imageView?.image = UIImage(named: "PlaceholderImage")
if let imageUrl = preview.imageUrl {
let url = URL(string: imageUrl)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async {
cell.imageView?.image = UIImage(data: data!)
}
}.resume()
}
} else {
}
return cell
}
在您的情况下,您不应使用 self.array 作为 table 视图的来源,相反,您应该声明一个代理变量并将其用作来源,例如:
var displayArray: [YourClass] {
return array.filter({ (YourClass) -> Bool in
return /*Your condition here*/
})
}
然后在您的 table 视图数据源中:
func numberOfSections(in tableView: UITableView) -> Int {
return displayArray.count
}
然后对 cellForRowAtIndexPath 应用相同的想法