2016-05-15 80 views
0

我是新来的swift,我现在的问题是我想将RoutePreviewController页面的值传回ViewController页面,点击导航按钮后显示。如下图所示,您可以看到RoutePreviewController不是直接从ViewController继承。Swift - 将值传递给使用协议和委托的ViewController

This is my story board of the swift project on xcode

然而,我尝试使用协议和委托中的代码。

下面是我添加到ViewController(的MainPage)代码

protocol HandleSelectedPath{ 
    func selectedPathDraw(selectedRoute:[(line:Int?,node:Int,time:Double)]) 
} 

在视图控制器

let routePreviewPage = storyboard!.instantiateViewControllerWithIdentifier("RoutePreviewController") as! RoutePreviewController 
    routePreviewPage.handleSelectedPathDelegate = self 

的viewDidLoad中和的ViewController类外的延伸

extension ViewController : HandleSelectedPath{ 
    func selectedPathDraw(selectedRoute:[(line:Int?,node:Int,time:Double)]){ 
     print("7687980") 
     selectedPath = selectedRoute 
     routeDraw() 
    } 
} 

而且在RoutePreviewController中,我有该协议的委托。

var handleSelectedPathDelegate: HandleSelectedPath? = nil 

和导航按钮动作

@IBAction func navigateButtonAction(sender: AnyObject) { 
    handleSelectedPathDelegate?.selectedPathDraw(previewPath) 
    dismissViewControllerAnimated(true, completion: nil) 
    definesPresentationContext = true 
} 

结果,点击浏览按钮后,它确实给我回的ViewController页,但不执行协议的selectedPathDraw功能。我也尝试打印一些随机字符串,但没有出现任何输出。

回答

0

根据您上面的代码只有你viewDidLoad内部存在,你必须设置为属性,而不是像这样为你RoutePreviewController参考:

var routePreviewPage: RoutePreviewController! 

始终是一个很好的做法实现你delegate为弱引用避免保留周期,所以将委派和协议的正确方法应该是如下面的代码:

protocol HandleSelectedPath: class { 
    func selectedPathDraw(selectedRoute:[(line:Int?,node:Int,time:Double)]) 
} 

RoutePreviewController

weak var handleSelectedPathDelegate: HandleSelectedPath? 

@IBAction func navigateButtonAction(sender: AnyObject) { 
    handleSelectedPathDelegate?.selectedPathDraw(previewPath) 
    dismissViewControllerAnimated(true, completion: nil) 
    definesPresentationContext = true 
} 

视图控制器viewDidLoad

routePreviewPage = storyboard!.instantiateViewControllerWithIdentifier("RoutePreviewController") as! RoutePreviewController 
routePreviewPage.handleSelectedPathDelegate = self 

我希望这可以帮助您。

+0

我试过了,但还是没有出来。 –

+0

你可以在Github分享你的代码吗? –

+0

我在bitbucket上找到了一个。这里是下载链接https://bitbucket.org/bhbo/smartcommuter/downloads –

相关问题