基于 Storyboard 多种方式的页面跳转、参数传递
生活随笔
收集整理的這篇文章主要介紹了
基于 Storyboard 多种方式的页面跳转、参数传递
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文
通過按鈕關聯跳轉
選中 Button ,然后點擊 action 右邊拖拽到 第二個頁面
選擇 “Show”即可完成跳轉關聯。
定義頁面間 segue Id,通過代碼觸發跳轉
選中第一個頁面,點擊manual右邊拖拽到第二個頁面
選中 show即可關聯兩個頁面
點擊中間的關聯點,修改 Segue Id
通過 Segue Id 跳轉
@IBAction func onButtonClick(_ sender: Any) {self.performSegue(withIdentifier: "ToSecondView", sender: nil) }通過 Storyboard ID 跳轉
設置第二個頁面的 Storyboard ID
通過 Storyboard 的文件名稱和頁面的 ID獲取到ViewController,通過pushViewController跳轉。
@IBAction func onButtonClick(_ sender: Any) {let sb = UIStoryboard(name: "Moments", bundle:nil)let vc = sb.instantiateViewController(withIdentifier: "SecondView")self.navigationController?.pushViewController(vc, animated: true)}傳遞參數
傳輸參數到第二個頁面
class SecondViewController: UIViewController {var param:String = ""override func viewDidLoad() {super.viewDidLoad()print("param:\(param)")} }傳輸參數非常簡單,只要覆蓋 prepare 方法,在方法中設置參數即可。
class FirstViewController: UIViewController {override func viewDidLoad() {super.viewDidLoad()}override func prepare(for segue: UIStoryboardSegue, sender: Any?) {if(segue.destination is SecondViewController){let vc = segue.destination as! SecondViewControllervc.param = "Wiki"}} }運行結果:
param:Wiki
返回參數:第一種方式
class FirstViewController: UIViewController {var param:String = ""override func viewDidAppear(_ animated: Bool) {// 在這里處理返回值print("返回值:\(param)")}... } class SecondViewController: UIViewController {...@IBAction func onCloseClick(_ sender: Any) {let vc = self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count)! - 2] as! FirstViewControllervc.param = "收到啦"self.navigationController?.popViewController(animated: true)} }結果
返回值:收到啦
返回參數第二種方式:通過 NotificationCenter 返回值
定義監聽器
override func viewDidLoad() {super.viewDidLoad()let notificationName = Notification.Name("UploadStatus")NotificationCenter.default.addObserver(self, selector: #selector(updateStatus), name: notificationName, object: nil) } @objc func updateStatus(notification: Notification){if(notification.object != nil){print("2上傳狀態:\(notification.object!)")}if(notification.userInfo != nil){print("2參數:\(notification.userInfo!)")} }發送通知
let notificationName = Notification.Name("UploadStatus") NotificationCenter.default.post(name: notificationName, object: "上傳失敗") NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["param1":"Wiki","param2":18])轉載于:https://www.cnblogs.com/taoweiji/p/10915534.html
總結
以上是生活随笔為你收集整理的基于 Storyboard 多种方式的页面跳转、参数传递的全部內容,希望文章能夠幫你解決所遇到的問題。

- 上一篇: 「AHOI / HNOI2018」转盘
- 下一篇: Android线程池封装库