簡體   English   中英

從第二視圖(Swift)到第一視圖的初始功能

[英]Initial func in 1st view from 2nd view (swift)

我在第二個viewController上有一個按鈕,按下該按鈕后,我想關閉第二個viewController並返回到第一個視圖控制器,並立即調用在第一個ViewController swift文件中編碼的函數

我可以知道該怎么做嗎? 通過segue?

有許多方法可以做到這一點,最好的方法之一就是使用protocoldelegate

您可以創建一個protocol並在ViewController1擴展該協議。 現在,在ViewController2創建協議的delegate ,並在ViewController1's prepareForSegue方法中傳遞該委托的引用。

首先創建一個這樣的協議

protocol PassdataDelegate {

    func passData()
}

現在像這樣在ViewController1擴展此協議,並在prepareForSegue方法中傳遞委托的引用

class ViewController1 : UIViewController, PassdataDelegate {


    func passData() {
        //Here call your function 
        self.callMyFunction()
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "SegueIdentifier") {
             let destVC = segue.destinationViewController as! ViewController2
             destVC.delegate = self 
        }
    }
}

現在像這樣在ViewController2創建protocol的委托對象

class ViewController2 : UIViewController {

    var delegate: PassdataDelegate?

    //Now call the method of this delegate in Button action
    @IBAction func buttonClick(sender: UIButton) {
         self.delegate.passData()
         //Now dismiss the controller
    }
}

注意:-我在這里傳遞string但是您可以傳遞在delegate方法中聲明的任何類型的對象。

您可以參考unwind segue

class ViewController1 {
  @IBAction func doSomeStuffAfterReload(segue: UIStoryboardSegue) {
    // do whatever you need to do here.
  }
}

在情節doSomeStuffAfterReload ,從ViewController2按住Ctrl並從button拖動到exit outlet然后選擇doSomeStuffAfterReload

您可以在這里看到它的運行情況: https : //spin.atomicobject.com/2014/10/25/ios-unwind-segues/快樂編碼^^

暫無
暫無

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

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