我有一个带有导航控制器的简单程序,并创建了序列以在3-5个屏幕之间切换。数据在主视图控制器中,我已经在主视图控制器和第二个视图控制器之间正确设置了委托和协议。我遇到的问题是我不确定如何在主视图和第三个视图之间建立适当的委托。我的主要困扰在于prepareForSegue函数的重写。

因为程序一次流过一个屏幕(主视图切换到第二视图,第二视图切换到第三视图,依此类推),所以我不确定应该在哪里以及如何使用此功能。我已经将主视图设置为遵守第三视图控制器协议,但是我不确定如何将其设置为委托。

例如,我知道如果我在第二个视图控制器中重写prepareForSegue函数,则不能使用“ self”作为委托。我想使主视图成为委托,但是我不确定使非“自我”视图成为委托的语法是什么。

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "2ndViewTo3rdView"{
        let thirdVC:ThirdViewController = segue.destinationViewController as ThirdViewController
        thirdVC.delegate = (????)
    }
}


我尝试了一些类似“ navigationController?.topViewController”的操作,但是出现以下错误:类型“ UIViewController”不符合协议“ ThirdViewDelegate”

在这方面的任何帮助将不胜感激。

最佳答案

我已将此解决方案用于模态呈现的VC,其中:


customVCOneA可能会呈现customVC3
-要么-
customVCOneB可能会呈现customVC2
-然后-
customVCTwo提出customVCThree
customVCThree仅在customVCOneB上发送指令以清除表单数据。


对于Swift 5:

在customVCThree中(发送说明或信息)

课外:

// Establish protocol for communicaiton back to parent view controller.
protocol ClearVCOneBProtocol {

    // State the method that communicates back to grandparent view controller.
    func clearVCOneB(/*Other Desired Parameters*/)

}


在类内部(不在任何函数中):

// Declare the delegate used to communicate with parent view controller.
var delegate: ClearVCOneBProtocol?


在类内部(您的应用所需的触发器协议方法):

    // As View Controller is about to disappear.
    override func viewWillDisappear(_ animated: Bool) {

        // Check "Restoration Identifier" (set inside Interface Builder or by code).
        if presentingViewController?.restorationIdentifier == "customVCTwo" {

            // Instruct the delegate to clear the form.
            delegate?.clearVCOneB()

        }
        else {

            // Do NOT instruct the delegate to clear the form.

        }

    }


在customVCOneB中(接收说明或信息)

课外:

// Extend the View Controller with the protocol and delegate methods.
extension customVCOneB: ClearVCOneBProtocol {

    // Conform to ClearVCOneBProtocol protocol.
    func ClearVCOneBProtocol(/*Other Desired Parameters*/) {

        // Call a function that has been declared inside customVCOneB and/or access parameters included in protocol.
        resetForm()

    } // End ClearVCOneBProtocol.

} // End extension.


在customVCTwo中(介于customVCOneB和customVCThree之间的中介)

实例化并显示customVCThree的位置:

    // Create the View Controller.
    let newVC = self.storyboard?.instantiateViewController(withIdentifier: customVCThree) as! customVCThreeViewController

    // If customVCTwo was presented by customVCOne...
    if presentingViewController?.restorationIdentifier == "customVCOneB" {

        // Set customVCOneB as the delegate of customVCThree.
        customVCThree.delegate = presentingViewController as! customVCOneBViewController

    }

关于ios - 将Swift委托(delegate)设置为除“self”以外的 View Controller 的语法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27221998/

10-14 23:26