Swift委托协议未调用

时间:2019-01-15 04:29:53

标签: swift delegates protocols

我是Swift的初学者。我正在尝试使用委托和协议将数据从子视图向后发送到根视图(在导航控制器中)

这是我的代码:

    <soap-env:Body>
        <OTA_AirAvailRS xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stl="http://services.sabre.com/STL/v01" Version="2.0.0">
            <stl:ApplicationResults status="NotProcessed">
                <stl:Error type="Application" timeStamp="2019-01-14T22:16:07-06:00">
                    <stl:SystemSpecificResults>
                        <stl:Message>Unexpected request processing error</stl:Message>
                        <stl:ShortText>ERR.SWS.PROVIDER.REQUEST_HANDLER_ERROR</stl:ShortText>
                    </stl:SystemSpecificResults>
                </stl:Error>
            </stl:ApplicationResults>
        </OTA_AirAvailRS>
    </soap-env:Body>

这是我从Filter呼叫代表的地方

//FilterViewController.swift:

protocol FilterDelegate: class {
    func finishFilter(query: String);
}

class FilterViewController:BaseViewController,....{
    ....
    weak var delegate : FilterDelegate?

    @IBAction func acceptTapped(_ sender: UIButton) {
        var querystring = ""
        var conditions: [String] = []
        //some logic works with conditions
        querystring = conditions.joined(separator: "&")
        self.delegate?.finishFilter(query: querystring)
        self.navigationController?.popViewController(animated: true)
    }
}

委托没有调用我的finishFilter函数。相反,当我在FilterController中弹出视图时,它直接进入HouseListController中的viewWillAppear,并停留在那里,而没有任何对委托的调用。

我想念什么吗?

2 个答案:

答案 0 :(得分:0)

您在filterTapped中显示的代码就是问题所在。您从情节提要中创建了FilterViewController的新实例,但从未设置该实例的delegate属性。

我会摆脱您的filterController财产。摆脱viewDidLoad中设置其delegate的那一行。您从未使用过该代码,因此您不需要它。

然后更新filterTapped

@IBAction func filterTapped(_ sender: UIButton) {
    self.currentMode = .filter
    self.tracking.previousMode = .filter
    let filterController = storyboard?.instantiateViewController(withIdentifier: "FilterView") as! FilterViewController // Update this line
    filterController.delegate = self // Add this line
    self.navigationController?.pushViewController(self.filterController, animated: true)
}

答案 1 :(得分:0)

如果要向后发送数据,请使用闭包。假设您有两个ViewController A和B,并且您希望数据从B到A,则在B ViewController中声明关闭。

class B_ViewController: UIViewController{
   var closureData: ((NSMutableArray) -> Void) = { arg in }

    @IBAction func onBtnDoneClick(_ sender: Any) {
        self.closureData(self.selectedClosureArray)
        self.navigationController?.popViewController(animated: true)
    }
}

现在视图控制器A中的调用关闭在视图控制器B中声明。 这里的A_VC_arrayNSMutableArray,而bVC是Viewcontroller B的对象。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    self.bVC.closureData  = { (selectedClosureData:NSMutableArray) -> Void in
        self.A_VC_array = selectedClosureData
    }
}