ios - 如何过滤数组以更新 TableView ?

标签 ios arrays swift xcode filter

你好我是 Swift 的新手,我在过滤数组后遇到问题我无法将它更新到我的 tableview

我尝试使用 filter() 但我不知道如何更新 tableview.reloadData() 不起作用。

这些代码是在按钮的 IBAction 方法中编写的。我想在点击按钮时喜欢它会使用过滤器更新 tableview 但会收到如下警告

Result of call to 'filter' is unused

   @IBAction func oneTapped(_ sender: Any) {

    if staroneBtn.isSelected == true{

        staroneBtn.setBackgroundImage(#imageLiteral(resourceName: "1stared"), for: .normal)
        hotelArray.filter(){$0.star == 1}
        self.tbView.reloadData()

    } else if staroneBtn.isSelected == false{
        staroneBtn.setBackgroundImage(#imageLiteral(resourceName: "1star"), for: .normal)
    }
    staroneBtn.isSelected = !staroneBtn.isSelected
}

@IBAction func twoTapped(_ sender: UIButton) {

    if startwoBtn.isSelected == true{
        startwoBtn.setBackgroundImage(#imageLiteral(resourceName: "2stared"), for: .normal)
        hotelArray.filter(){$0.star == 2}
        self.tbView.reloadData()
}else if startwoBtn.isSelected == false{
        startwoBtn.setBackgroundImage(#imageLiteral(resourceName: "2star"), for: .normal)
    }
    startwoBtn.isSelected = !startwoBtn.isSelected

}

就我所做的研究而言,我发现我需要更改 CellforRows 函数,但我不知道该怎么做。

请帮忙。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   guard let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as? HotelTableViewCell else{return UITableViewCell()}

    cell.NameLbl.text = hotelArray[indexPath.row].hotelName

    return cell
}

最佳答案

警告本身说你需要像下面这样使用过滤器的结果......

 hotelArray = hotelArray.filter {$0.star == 1}

您需要将 hotelArray 设为 var

关于ios - 如何过滤数组以更新 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54566619/

相关文章:

ios - 如何绑定(bind) SwiftUI 和 UIViewController 行为

ios - 自定义 UIMenuController 问题

objective-c - 更改 MKAnnotationView 自定义图像?

c - (C) 使用数组进行动态内存分配

javascript - 将字符串解析为数组

ios - 计算属性中的自调用

iphone - 分发使用其他代码的自定义 View

ios - 如何将 TableView 中选定的行字符串传递到另一个 ViewController 页面? ( swift 2)

c++ - 设置动态数组的默认值

swift - 如何在 Swift 中正确测量后台运行时间