簡體   English   中英

如何將選定單元格的值傳遞給另一個ViewController?

[英]How pass the value of a selected cell to another ViewController?

本質上,我有以下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
    }

}

為要傳遞給ScheduledDelivery控制器的數據創建公共變量。然后在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)

在下一個ViewController中添加一個Portfolio變量

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

您可以將單元格的數據存儲為變量,然后在准備segue函數時將其傳遞給另一個ViewController。 如果您在准備segue時調用它,它將在您每次嘗試訪問此segue時自動執行。

var nameOfVar:String =“”

覆蓋func prepare(用於segue:UIStoryboardSegue,發件人:任意?){
var secondVC = segue.destination為! YourSecondViewController
secondVC.variable = nameOfVar}

希望我有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM