2016-05-15 79 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 –

相關問題