首页 > 解决方案 > Swift UITableView:如何从选定的单元格中收集数据

问题描述

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

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

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

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

标签: iosswiftuitableviewsegue

解决方案


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)
    }
}

在情节提要中设置 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


推荐阅读