簡體   English   中英

從子 UIViewController 調用父 UIViewController 方法

[英]calling a parent UIViewController method from a child UIViewController

我有一個父 UIViewController,它打開一個子 UIViewController:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)

我按下 ChildView 中的一個按鈕,它應該關閉 ChildView 並在父視圖中調用一個方法:

self.dismissViewControllerAnimated(true, completion: nil)
CALL PARENTS METHOD  ??????

怎么做 ? 我找到了一個很好的答案( 鏈接到好的答案),但我不確定這是否是 UIViewControllers 的最佳實踐。 有人可以幫忙嗎?

實現此目的的一種簡單方法是使用NSNotificationCenter

在您的ParentViewController添加到viewDidLoad方法中:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: Selector(("refresh:")), name:NSNotification.Name(rawValue: "refresh"), object: nil)
}

之后在ParentViewController中添加這個函數,當你關閉你的ChildViewController時它會被調用:

func refreshList(notification: NSNotification){

    print("parent method is called")
}

並在您的ChildViewController添加此代碼,您可以在其中關閉子視圖:

 @IBAction func btnPressed(sender: AnyObject) {

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refresh"), object: nil)
    self.dismiss(animated: true, completion: nil)
}

現在,當您關閉子視圖時,將調用refreshList方法。

向子視圖控制器添加一個弱屬性,該屬性應包含對父視圖控制器的引用

class ChildViewController: UIViewController {
weak var parentViewController: UIViewController?
....
}

然后在你的代碼中(我假設它在你的父視圖控制器中),

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("myChildView") as! ChildViewController
vc.parentViewController = self
self.presentViewController(vc, animated: true, completion: nil)

而且,正如 vomako 所說,在解除子視圖控制器之前調用父方法。

parentViewController.someMethod()
self.dismissViewControllerAnimated(true, completion: nil)

或者,您也可以在dismissViewControllerAnimated的完成參數中調用該方法,它會您的子視圖控制器關閉運行:

self.dismissViewControllerAnimated(true) {
    parentViewController.someMethod()
}

我在您的問題中注意到的一些事情:在解除視圖控制器后不要調用方法(在您的情況下為父方法)。 關閉視圖控制器將導致它被釋放。 以后的命令可能無法執行。

您在問題中包含的鏈接指向了一個很好的答案。 在你的情況下,我會使用委托。 在關閉子視圖控制器之前調用父視圖控制器中的委托方法。

這是一個很好的教程

protocol SampleProtocol 
{
    func someMethod()
}   


class parentViewController: SampleProtocol 
{
    // Conforming to SampleProtocol
    func someMethod() {
    }
}

 class ChildViewController
    {
        var delegate:SampleProtocol?
    }

    self.dismissViewControllerAnimated(true, completion: nil)
    delegate?.someMethod()

暫無
暫無

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

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