【问题标题】:Swift - Passing value back to ViewController using protocol and delegateSwift - 使用协议和委托将值传递回 ViewController
【发布时间】:2016-05-16 18:34:35
【问题描述】:

我是 swift 新手,我现在的问题是我想在单击导航按钮后将值从 RoutePreviewController 页面传回以显示在 ViewController 页面上。如下图,你可以看到 RoutePreviewController 不是直接从 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)])
}

在 ViewController 的 viewDidLoad 中

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

以及 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
}

因此,在单击 Navigate 按钮后,它确实将我送回 ViewController 页面,但未执行协议的 selectedPathDraw 功能。我也尝试打印一些随机字符串,但没有输出。

【问题讨论】:

    标签: ios swift protocols


    【解决方案1】:

    根据您上面的代码,您的RoutePreviewController 的引用只存在于您的viewDidLoad 中,您必须像这样设置为属性:

    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 of ViewController

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

    希望对你有所帮助。

    【讨论】:

    • 我在 bitbucket 上找到了一个。这是下载链接bitbucket.org/bhbo/smartcommuter/downloads
    • 我刚刚下载了你的代码,但它有点大,我不知道如何到达RoutePreviewController
    • 如果您在 Xcode 上打开项目,您必须找到“Controller”文件夹,ViewController 和 RoutePreviewController 都存储在该文件夹中。
    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多