【问题标题】:Initial func in 1st view from 2nd view (swift)从第 2 视图到第 1 视图的初始 func (swift)
【发布时间】:2016-07-15 04:21:26
【问题描述】:

我在第二个viewController 上有一个按钮,按下该按钮后,我想关闭第二个viewController 并返回到第一个视图控制器并立即调用编码的函数在第一个 ViewController swift 文件中。

我可以知道我该怎么做吗?通过转场?

【问题讨论】:

  • 您可以将第一个视图控制器设置为第二个视图控制器的委托属性。按下按钮时,将委托函数调用到第一个视图控制器
  • 当第二个视图控制器出现时,传递一个闭包作为回调并在IBAction中调用闭包。

标签: ios swift segue


【解决方案1】:

有很多方法可以做到这一点,其中一种最好的方法是使用 protocoldelegate

您可以创建一个protocol 并在您的ViewController1 中扩展该协议。现在在ViewController2 中创建协议的delegate,并在ViewController1's prepareForSegue 方法中传递该委托的引用。

首先创建一个这样的协议

protocol PassdataDelegate {

    func passData()
}

现在像这样在ViewController1 中扩展这个协议,并在prepareForSegue 方法中传递委托的引用

class ViewController1 : UIViewController, PassdataDelegate {


    func passData() {
        //Here call your function 
        self.callMyFunction()
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "SegueIdentifier") {
             let destVC = segue.destinationViewController as! ViewController2
             destVC.delegate = self 
        }
    }
}

现在像这样在ViewController2中创建protocol的委托对象

class ViewController2 : UIViewController {

    var delegate: PassdataDelegate?

    //Now call the method of this delegate in Button action
    @IBAction func buttonClick(sender: UIButton) {
         self.delegate.passData()
         //Now dismiss the controller
    }
}

注意:-我在这里传递string,但您可以传递您在delegate 方法中声明的任何类型的对象。

【讨论】:

  • 感谢您的快速回复,但如果我只想关闭第二个视图并在第一个视图中调用 func 而不传递任何字符串?如何更改上面的代码?
  • 我已经编辑了答案,在ViewController1 中添加了委托方法,现在在委托方法中调用您的方法。
  • 谢谢,确实很有帮助。
  • 欢迎小伙伴快乐编码:)
  • 当我将函数从 ViewController2 传递到 ViewController1 时,出现以下错误“在展开可选值时意外发现 nil”。发生了什么?我的函数只是 Print("test")
【解决方案2】:

您可以参考unwind segue

class ViewController1 {
  @IBAction func doSomeStuffAfterReload(segue: UIStoryboardSegue) {
    // do whatever you need to do here.
  }
}

在情节提要上,从 ViewController2 Ctrl+Drag 从buttonexit outlet 并选择doSomeStuffAfterReload

您可以在这里看到它的实际效果:https://spin.atomicobject.com/2014/10/25/ios-unwind-segues/ 快乐编码^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    相关资源
    最近更新 更多