gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:46:25 25 4
gpt4 key购买 nike

我正在尝试将用户在我的 ShipViewController 中选择的名称的数据传递到我的 ProfileViewController。我尝试使用闭包来这样做,但是 ProfileViewController 中的按钮标题(它向 ShipViewController 显示模态弹出窗口)没有更改为用户在ShipViewController

它不应该是 String --> () 还是我实例化 View Controller 的方式不正确?

(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)
}

最佳答案

didSelectItemAt 中关闭 ShipViewController

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)
}
}
}
}

关于swift - 使用闭包将变量信息传递给第一个 VC 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55349677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com