iOS - 将 tableView 中的 numberOfSections 设置为过滤单元格的数量 (Swift)

标签 ios swift uitableview filter sections

我已经设置了我的 tableView,因此它根据数组的每个子项(factor1 和 factor2)与 2 个用户输入(factor1UserInput 和 factor2UserInput)匹配的 2 个因子的值进行过滤。问题是 - 因为我将我的 numberOfSections 设置为返回 array.count - 它会为数组中的每个子项加载所有单元格,包括未填充的单元格。

因此,我试图将我的 tableView 中的 numberOfSections 设置为过滤单元格(我正在填充的单元格)的数量 - 除非有更好的方法来过滤这些单元格以便不加载未填充的单元格。

numberOfSections 代码:

func numberOfSections(in tableView: UITableView) -> Int {
    return array.count
}

表格 View 代码:

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 作为 tableView 的源,相反,您应该声明一个代理变量并将其用作源,例如:

var displayArray: [YourClass] {
    return array.filter({ (YourClass) -> Bool in
        return /*Your condition here*/
    })
}

然后在您的 TableView 数据源中:

func numberOfSections(in tableView: UITableView) -> Int {
    return displayArray.count
}

然后对 cellForRowAtIndexPath 应用相同的想法

关于iOS - 将 tableView 中的 numberOfSections 设置为过滤单元格的数量 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107863/

相关文章:

ios - Swift:如何以正确的方式将 [[String]] 连接到 [String]?

iphone - UITableViewCell - 图像在 tableview 滚动时消失

ios - 从 TableViewController 获取 CustomCell 上的 UITextField 的委托(delegate)触发器和普通触发器之间有什么区别?

iphone - 类别,协议(protocol),一大类?我应该在这里使用什么

ios - 更改 Xcode 调试器变量 View 中显示的信息

ios - 如何检查 child 的数据,在 Firebase 的 child 中

ios - Swift - base64EncodingStringWithOptions 不工作 Xcode 6.1

swift - 在 switch 语句中匹配可选

ios - UIButtons 作为 TableView 中的复选框

ios - 无法将类型 '(TVSessionConfigurationBuilder!) -> Void' 的值转换为预期的参数类型 'TVSessionConfigurationBuilderBlock!'