Swift /如何使用popViewController调用委托

时间:2016-09-25 23:27:03

标签: ios swift

我从下到上阅读了this thread(和其他类似的人),但它根本不符合我的需求。

UIViewController内的UIPageViewController内有UINavigationController。导航到第二个ViewController。导航到第三个ViewController并想要弹回第二个ViewController来传递数据。

目前我的代码:

protocol PassClubDelegate {
            func passClub(passedClub: Club)
        }

class My3rdVC: UIViewController {

        var clubs: [Club] = []

        var passClubDelegate: PassClubDelegate?

....

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let club = clubs[indexPath.row]
        self.passClubDelegate?.passClub(club)
        navigationController?.popViewControllerAnimated(true)
    }

我的第二个VC:

class My2ndVC: UIViewController, PassClubDelegate {

    var club = Club()

    func passClub(passedClub: Club) {

        SpeedLog.print("passClub called \(passedClub)")
        club = passedClub
    }

passClub未被调用。我确定它是因为我没有将代表设置为My2ndVC,但我该怎么做?我发现的所有解决方案都希望我使用a)segue或b)实例化一个My2ndVC new,什么都没有任何意义,因为它仍然在内存中,我想回弹回到层次结构中。我错过了什么?我的可能性是什么?非常感谢帮助。

PS :我没有使用任何segues。 My3rdVC由:

调用
let vc = stb.instantiateViewControllerWithIdentifier("My3rdVC") as! My3rdVC
self.navigationController?.pushViewController(vc, animated: true)

1 个答案:

答案 0 :(得分:4)

您可以My3rdVC prepareForSegue方法设置My2ndVC的委托。

class My2ndVC: UIViewController, PassClubDelegate {

    ...

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        super.prepareForSegue(segue, sender: sender)

        switch segue.destinationController {
        case let controller as My3rdVC:
            controller.passClubDelegate = self
        }
    }
}

这假设您在故事板中创建了一个segue,它将My3rdVCMy2ndVC推送到导航控制器堆栈,我假设您已经拥有。因此,只需将此prepareForSegue方法粘贴到My2ndVC中,看看它是否有效。

更新

let vc = stb.instantiateViewControllerWithIdentifier("My3rdVC") as! My3rdVC

vc.passClubDelegate = self

navigationController?.pushViewController(vc, animated: true)