簡體   English   中英

在swift4中的ViewController之間傳遞數據

[英]Passing Data between ViewController in swift4

在此處輸入圖片說明

在上面的圖片中,有兩個視圖。 最上面的是一個用於顯示日期的視圖(此視圖的類名稱為calender view )。 最下面的是一個tableview。當前視圖的名稱是Main View。當我單擊tableview的單元格時,它將轉到下一個視圖 當我消除下一個視圖時,我想將一些數據傳遞到日歷視圖 。如何實現這一點。

class MainView: UIViewController, UITableViewDataSource, UITableViewDelegate {

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

        let next = self.storyboard?.instantiateViewController(withIdentifier: "NextVC") as! NextVC
        self.present(next, animated: true, completion: nil)

    }

}


class NextVC: UIViewController {

    var sendingData: String?

    @IBAction func backAction(_ sender: Any) {
        dismiss(animated: true, completion: nil)

    }
}


class CalenderView: UIViewController{

    var receiveValue: String?
}

在這里,我希望當我駁回新思維 sendingData的價值將通過壓延視圖

這個怎么做 ? 請幫忙。

我可以給你兩個解決方案:

  1. 您可以創建自定義通知。

首先,在后退操作上,您應該使用sendData發布通知。

NotificationCenter.default.post(name: NSNotification.Name(rawValue: UpdateCalendarNotification), object: sendingData)

接下來,在帶有日歷視圖的主視圖控制器上,您應該注冊“ UpdateCalendarNotification”名稱的通知。

    func registerNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(updateCalendarView(_:)),
                                               name: NSNotification.Name(rawValue: "UpdateCalendarNotification"),
                                               object: nil)
    }

在選擇器updateCalendarView(_:)您應該處理日歷視圖的更改。

    @objc
    func updateCalendarView(_ notification: NSNotification) {
        if let sendingData = notification.object as? String {
            /// Update calendar view
        }
    }
  1. 第二種解決方案是為您“下一個控制器”提供公共塊。

在下一個視圖控制器上,您應該添加以下處理程序:

    var onDismiss: ((String?) -> Void)?

backAction方法中,您應該傳遞數據

    onDismiss?(sendingData)

在主視圖控制器中,您應該像這樣實現此塊:

let next = self.storyboard?.instantiateViewController(withIdentifier: "NextVC") as! NextVC
next.onDismiss = { [weak self] (sendingData) in
    self?.calendarView.receiveValue = sendingData
}
self.present(next, animated: true, completion: nil)

我希望這能幫到您)

暫無
暫無

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

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