【问题标题】:Swift UITableView: How to collect the data from selected cellSwift UITableView:如何从选定的单元格中收集数据
【发布时间】:2018-09-04 04:40:16
【问题描述】:

我想知道在使用 UITableView 时如何从上一页收集数据。

很难解释,所以我举个例子。

Apple 默认日历应用在新活动页面中具有此功能。 当您打开“新偶数”页面时,您将在“重复”字段中看到“从不”。要更改此设置,您需要点击“从不”并转到下一页并选择“每周”之类的内容。如果您选择“每周”,它将返回到第一页,“重复”字段现在显示“每周”。

我想做一些类似的东西,但不知道如何设置......我的问题是;我需要使用 Segue 吗?我需要对单元格使用 UITextField 或 UILabel 吗?传递数据的触发器是什么?

【问题讨论】:

  • 欢迎加入 stackoverflow,您发布了尝试过的代码,我们可以帮助您解决问题
  • 一般来说,您要求在视图控制器之间传递数据。 stackoverflow.com/questions/5210535/…

标签: ios swift uitableview segue


【解决方案1】:

MainviewController 添加下面的代码

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // "SelectionSegue" is same as storyboard segue identifier
    if segue.identifier == "SelectionSegue" {
        (segue.destination as! SelectCategoryViewController).selectedCategoryValue = self.selectedCategoryLabel.text!
        print(selectedCategoryLabel)
    }
}

在 Storyboard 中设置 Segue 标识符

选择表视图

var selectedCategoryValue:String = ""
var CategeryArray = ["Food","Travel","Shopping","Card","MyReserve","Game","Songs","Movies","Entertainment","Business","Education","Finance","Drink","Sports","Social","Lifestyle"]

//添加TableView委托和数据源方法

extension SelectCategoryViewController: UITableViewDelegate,UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return CategeryArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell")!
        cell.textLabel?.text = self.CategeryArray[indexPath.row]

        if self.CategeryArray[indexPath.row] == self.selectedCategoryValue {
            cell.accessoryType = .checkmark
        } else {
            cell.accessoryType = .none
        } 

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
        self.selectedCategoryValue = CategeryArray[indexPath.row]
        self.tableView.reloadData()
    }
}

我的观点喜欢

NavigationController -> Mainview -> SelectedTableView

【讨论】:

  • 你不认为tableView.cellForRow(at: indexPath)?.accessoryType = .checkmarkdidSelectRowAt 方法中是不必要的吗?
  • 感谢 Ramprasathselvam!你能告诉我你在哪里声明了“selectedCategoryLabel”吗?
  • MainViewController "None" Text is selectCategoryLabel @Riki_U
  • 感谢 Ramprasathselvam!那么我是否将其添加为故事板中的标识符?还是我应该声明为变量?
  • 您可以在情节提要@Riki_U 中添加标识符
猜你喜欢
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 2016-11-24
  • 2017-05-24
  • 2015-04-10
  • 2021-10-20
  • 1970-01-01
  • 2011-04-27
相关资源
最近更新 更多