【问题标题】:Pass data from Modal view to Parent view using delegates (with a segue in storyboard)使用委托将数据从模态视图传递到父视图(在情节提要中使用 segue)
【发布时间】:2018-02-08 09:35:54
【问题描述】:

我正在尝试将一些数据从一个视图传递到下一个视图,但是我正在使用 segue(使用情节提要执行此操作)以在模态演示中打开第二个视图。

现在我正在使用委托将一些信息从打开的模式窗口传递回主视图...

它不起作用,它永远不会到达主窗口。不会崩溃。

我试过用这个: Inserting rows to tableView using modal popup(这实际上是我想要完成的)但我无法让它工作。我也错过了它说的部分

myPopUp.delegate = self 

因为我正在使用故事板转场,但我没有办法做到这一点......

请帮忙!


这是主控制器:

import UIKit

class HomeViewController: UIViewController, AddRowDelegate {
    public func didAddRow(name: String){
        print("reached HomeViewController") // This does NOT print
    }

    override func viewDidLoad(){
        super.viewDidLoad()
    }
}

这是模态窗口:

import UIKit

protocol AddRowDelegate {
    func didAddRow(name : String)
}

class ModalViewController: UIViewController {

    var delegate : AddRowDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func SendInfoBack(_ sender: Any) {
        delegate?.didAddRow(name: "whatever")
        print("Modal Window") // This part DOES print.
    }
}

【问题讨论】:

标签: ios swift delegates modalviewcontroller


【解决方案1】:

在 prepareForSegue 中设置委托

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if segue.identifier == "showModal"{
      let modalVC = segue.destination as! ModalViewController
      modalVC.delegate = self
   } 
}

【讨论】:

    【解决方案2】:

    如果我正确理解您的问题,您应该在目标视图中使用相同的数据类型并将其传递给准备函数

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toTabBar"{
            let destView = segue.destination as! UIView
            destView.data= dataToPass
        }
    }
    

    .

    【讨论】:

    • 这可能是比协议更好的解决方案。
    • destination 是 UIViewController ,你如何转换 as ! UIView ,第二个他想将数据从模态发送到父级而没有展开序列
    • 抱歉打错了我的意思是 UIViewController
    猜你喜欢
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2013-03-29
    相关资源
    最近更新 更多