【问题标题】:How do I use two buttons in Controller? Each button has a tableview?如何在 Controller 中使用两个按钮?每个按钮都有一个tableview?
【发布时间】:2019-07-26 08:14:48
【问题描述】:

我在控制器中使用了两个按钮 当我按下按钮 1 时,它应该显示与按钮 1 相关的表格视图 当我按下按钮 2 时,它显示与按钮 2 相关的表格视图 我怎样才能做到这一点?

【问题讨论】:

  • 只需使用bool 并在此基础上在data source 方法中填充您的tableView 数据。
  • 你想使用单个tableView还是2个tableView?
  • 另外,添加model和tableView dataSource的代码。
  • 好吧,我需要指导我应该使用两个 tableViews 还是使用两个单元格的单个 tableView 会起作用? @PGDev
  • 您绝对可以使用单个tableView,只要您可以为它们处理不同的数据源。添加更多详细信息,以便我可以更新我添加的答案。

标签: swift xcode uitableview


【解决方案1】:

首先,创建一个enum 来跟踪datacell 应该在tableView 中加载的内容,即

enum Source {
    case button1
    case button2
}

现在,您必须拥有 2 个arrays,用于按照source 加载tableView

例如:

class VC: UIViewController, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    var arr1 = ["one", "two"]
    var arr2 = ["three", "four"]
    var source = Source.button1

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch source {
        case .button1:
            return arr1.count
        case .button2:
            return arr2.count
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch source {
        case .button1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
            cell.textLabel?.text = arr1[indexPath.row]
            return cell
        case .button2:
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath)
            cell.textLabel?.text = arr2[indexPath.row]
            return cell
        }
    }
}

现在,为buttons 创建@IBAction,更新source 并在button 点击时重新加载tableView

@IBAction func onTapButton1(_ sender: UIButton) {
    self.source = .button1
    self.tableView.reloadData()
}

@IBAction func onTapButton2(_ sender: UIButton) {
    self.source = .button2
    self.tableView.reloadData()
}

【讨论】:

    【解决方案2】:

    我想,你要找的是SegmentedControl

    您应该使用 ViewController 作为页面的基础,在顶部添加分段控件,然后添加 tableView。然后使用分段控制来控制表格的来源。您的代码应如下所示:

    switch (segmentedControl.selectedSegmentIndex ) {
        case 0:
            yourDataCollection = someService.getData(); // depends on selected index
            self.tableView.reloadData()
        case 1:
            yourDataCollection = someService.getSomeOtherData();
            self.tableView.reloadData()
        default:
            return
    }
    

    或者,如果您想使用按钮而不是分段控制,您可以创建一个 bool/Int 值并将其存储在按钮点击时。代码几乎相同。

    【讨论】:

      猜你喜欢
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 2023-02-03
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多