基於 Storyboard 多種方式的頁面跳轉、參數傳遞

原文ide

經過按鈕關聯跳轉

選中 Button ,而後點擊 action 右邊拖拽到 第二個頁面post

image.png

選擇 「Show」便可完成跳轉關聯。code

image.png

定義頁面間 segue Id,經過代碼觸發跳轉

選中第一個頁面,點擊manual右邊拖拽到第二個頁面orm

image.png

選中 show便可關聯兩個頁面server

image.png

點擊中間的關聯點,修改 Segue Idblog

image.png

經過 Segue Id 跳轉get

@IBAction func onButtonClick(_ sender: Any) {
    self.performSegue(withIdentifier: "ToSecondView", sender: nil)
}

經過 Storyboard ID 跳轉

設置第二個頁面的 Storyboard ID
image.pngit

經過 Storyboard 的文件名稱和頁面的 ID獲取到ViewController,經過pushViewController跳轉。io

@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 方法,在方法中設置參數便可。form

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! SecondViewController
            vc.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! FirstViewController
        vc.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])
相關文章
相關標籤/搜索