使用闭包将变量信息传递给第一个VC时出现问题

时间:2019-03-26 04:04:04

标签: swift variables closures viewcontroller instantiation

我正在尝试将用户在我的ShipViewController中选择了姓名的数据传递给我的ProfileViewController。我尝试使用闭包这样做,但是ProfileViewController中的按钮标题(将模式弹出窗口呈现到ShipViewController)并未更改为用户在ShipViewController中选择的名称。

它不是String->()还是实例化视图控制器的方式不正确?

(ShipViewController)

var completionHandler:((String) -> ())?

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "shipCell", for: indexPath) as! ShipViewCell

    if selectedIndex == indexPath.row {
        let result = completionHandler?(shipNames[selectedIndex!])
        self.dismiss(animated: true, completion: nil)
    }
}

(In viewDidLoad of ProfileViewController)
        let vc = storyboard?.instantiateViewController(withIdentifier: "ShipViewController") as! ShipViewController
    vc.completionHandler = { (text) -> ()in
        print(text)
        self.shipButton.setTitle(text, for: .normal)
    }

1 个答案:

答案 0 :(得分:1)

关闭ShipViewController中的didSelectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let result = completionHandler?(shipNames[indexPath.item])
        self.dismiss(animated: true, completion: nil)
}

ProfileViewController中不要分配给viewDidLoad中的completionHandler

prepare for segue中分配给完成处理程序

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showShip" {
        if let vc = segue.destination as? ShipViewController {
             vc.completionHandler = { (text) -> ()in
                  print(text)
                  self.shipButton.setTitle(text, for: .normal)
             }
        }
    }
}