首页 > 解决方案 > 如何根据在 Swift iOS 中单击的按钮更改 tableView numberOfRows 和 Cells

问题描述

我的用户个人资料页面中有两个按钮,一个用于保存的商店商品,一个用于他的评论。

我希望当用户单击保存的按钮时,它将在表格视图中加载他保存的商店的商品,当他单击评论按钮时,它将加载他的评论。

我正在努力弄清楚如何做到这一点

请问有什么帮助吗?

这是我的代码:

@IBOutlet weak var reviewsBtn: UIButton!
@IBOutlet weak var saveBtntab: UIButton! 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if(reviewsBtn.isSelected == true){
            print("review selected")
            return reviews.count
        }
        if(saveBtntab.isSelected == true){
            print("saved selected")
            return shops.count
        }
          return shops.count
      }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

 let cell = tableView.dequeueReusableCell(withIdentifier: "cellFave", for: indexPath) as! FaveTableViewCell
        let shops = self.shops[indexPath.row]
        let reviews = self.reviews[indexPath.row]
// i want to do the same idea for the number of rows here.
}

  @IBAction func reviewsTapped(_ sender: Any) {
        reviewsBtn.isSelected = true
        reviewsBtn.isEnabled = true
        faveBtntab.isEnabled = false
        faveBtntab.isSelected = false
    }
    
    @IBAction func savedTapped(_ sender: Any) {
        faveBtntab.isSelected = true
        faveBtntab.isEnabled = true
        reviewsBtn.isEnabled = false
        reviewsBtn.isSelected = false
      
    }

标签: iosswiftuitableviewuibutton

解决方案


首先,如果只有两种状态,您可以简化numberOfRows

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return reviewsBtn.isSelected ? reviews.count : shops.count
}

cellForRow做同样的事情时,显示项目取决于 reviewsBtn.isSelected

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     let cell = tableView.dequeueReusableCell(withIdentifier: "cellFave", for: indexPath) as! FaveTableViewCell
     if reviewsBtn.isSelected {
          let reviews = self.reviews[indexPath.row]
          // assign review values to the UI
     } else {
          let shops = self.shops[indexPath.row]
          // assign shop values to the UI
     }
}

并且不要忘记reloadData在状态发生变化时调用。


推荐阅读