【问题标题】:How pass the value of a selected cell to another ViewController?如何将选定单元格的值传递给另一个 ViewController?
【发布时间】:2019-06-26 18:36:14
【问题描述】:

基本上,我有以下UITableViewController,其中包含带有标签的自定义 tableView 单元格。选择单元格后,我希望将单元格的值传递给下一个视图控制器,我在 HTTP POST 响应中使用它。

可以添加什么到didSelectRowAt 以将选定单元格的值传递给呈现的视图控制器?

也许是一个变量?

以下是我的代码:

import UIKit

class ScheduledCell: UITableViewCell {

    @IBOutlet weak var ETALabel: UILabel!
    @IBOutlet weak var cellStructure: UIView!

    @IBOutlet weak var scheduledLabel: UILabel!
    @IBOutlet weak var testingCell: UILabel!
    @IBOutlet weak var pickupLabel: UILabel!
    @IBOutlet weak var deliveryLabel: UILabel!
    @IBOutlet weak var stopLabel: UILabel!
    @IBOutlet weak var topBar: UIView!


}

class ToCustomerTableViewController: UITableViewController, UIGestureRecognizerDelegate {

    var typeValue = String()

    var driverName = UserDefaults.standard.string(forKey: "name")!
    var structure = [AlreadyScheduledStructure]()


    override func viewDidLoad() {
        super.viewDidLoad()

        fetchJSON()


        //Disable delay in button tap
        self.tableView.delaysContentTouches = false

        tableView.tableFooterView = UIView()

    }


    private func fetchJSON() {
        guard let url = URL(string: "https://example.com/example/example"),
            let value = driverName.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
            else { return }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "driverName=\(value)".data(using: .utf8)

        URLSession.shared.dataTask(with: request) { data, _, error in
            guard let data = data else { return }


            do {
                self.structure = try JSONDecoder().decode([AlreadyScheduledStructure].self,from:data)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
            catch {
                print(error)
            }

            }.resume()

    }



    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return structure.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "scheduledID", for: indexPath) as! ScheduledCell
        let portfolio = structure[indexPath.row]
        cell.stopLabel.text = "Stop \(portfolio.stop_sequence)"
        cell.testingCell.text = portfolio.customer
        return cell

    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


        let portfolio = structure[indexPath.row]
        let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery")

        print(portfolio.customer)
        controller.navigationItem.title = navTitle
        navigationController?.pushViewController(controller, animated: true)
    }


    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200.0
    }

}

【问题讨论】:

    标签: ios swift uitableview uitableviewrowaction


    【解决方案1】:

    为要传递给 scheduleDelivery 控制器的数据创建公共变量。然后将它们设置在 didselect 委托方法中。假设你想通过portfolio.customer。在 scheduleDelivery 控制器上声明以下公共变量。

    public var portfilio:String?
    

    然后像这样通过didselect 方法为该变量设置值,

    let portfolio = structure[indexPath.row]
    let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery")
    controller.portfilio = portfolio.customer
    controller.navigationItem.title = navTitle
    navigationController?.pushViewController(controller, animated: true)
    

    【讨论】:

    • 我不断收到错误Value of type 'UIViewController' has no member 'portfolio'
    • 能把scheduledDeelivery控制器的源码放在这里吗?
    【解决方案2】:

    将投资组合变量添加到您的下一个 ViewController

       class scheduledDeleivery: UIViewController{
         var customer:String? //suposing this is customer type
    

    然后在 覆盖 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let portfolio = structure[indexPath.row]
        let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery") as! shcheduledDeleivery
        controller.customer = porfolio.customer //here is the customer you need to pass to next viewcontroller
        print(portfolio.customer)
        controller.navigationItem.title = navTitle
        navigationController?.pushViewController(controller, animated: true)
    }
    

    【讨论】:

    • 我不断收到'UIViewController' has no member 'portfolio'类型的错误值
    • 不完全是,我需要传递结构[index.row]的值
    • porfolio 的类型为 AlreadyScheduledStructure,因此在您的下一个视图控制器中必须有一个该类型的变量从 tableViewController 传递,所以当您使用这一行 let portfolio = structure[indexPath.row] 时,您需要使用该值传递到下一个视图控制器,使用 'let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "scheduledDelivery") 行作为! shcheduledDeelivery controller.porfolio = porfolio' 这一项将此处读取的值设置为下一项。
    • 问题在于 AlreadyScheduledStructure 的所有值都被传递了
    • 它正在传递整个结构的值,而我只需要客户AlreadyScheduledStructure: Codable { let customer: String let PickedUpNUM: String
    【解决方案3】:

    您可以将单元格的数据存储为变量,然后在准备 segue 函数时将其传递给另一个 ViewController。如果您在为 segue 做准备时调用它,它会在您每次尝试访问该 segue 时自动执行。

    var nameOfVar : String = ""

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    var secondVC = segue.destination as! YourSecondViewController
    secondVC.variable = nameOfVar }

    希望我有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2019-07-05
      相关资源
      最近更新 更多