gpt4 book ai didi

ios - Swift:在 dismissViewControllerAnimated 上将字符串值从 VC2 传递到 VC1

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

在这里学到了很多有用的东西,第一次提问!

我有一个带有按钮和标签的 VC1。该按钮被编码为以编程方式呈现 VC2(在 IB 中没有 segue)。VC2 有一个表格 View ,其中的单元格包含字符串值。

当我在 VC2 中单击单元格时,我试图获取所选单元格的字符串值并将其传递回 VC1 中的 label.text。

第一个 ViewController 代码:

class VC1: UIViewController {
... ...

@IBOutlet weak var LabelText: UILabel!
var passedString = "Example"

override func viewWillAppear(animated: Bool) {
LabelText.text = "\(passedString)"
}

@IBAction func chooseLabelTextBtnPressed(sender: AnyObject) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("VC2") as! VC2
self.presentViewController(vc, animated: true, completion: nil)
}

SecondViewController代码:

class VC2: UIViewController, UITableViewDelegate, UITableViewDataSource {    
... ...

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow;
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! VC2_tableViewCell!;
let valueToPass = currentCell.IBOutletLbl.text
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewControllerWithIdentifier("VC1") as! VC1
viewController.passedString = valueToPass!

//self.presentViewController(viewController, animated: true , completion: nil)

self.dismissViewControllerAnimated(true, completion: nil)
}

我希望 VC1 中的 func viewWillAppear() 会在 VC2 关闭时更新标签的字符串值,但事实并非如此。

我不能从 VC2 到 VC1 使用 presentViewController,因为它可能会再次打开 VC1 而不是返回,然后 VC1 中的其他变量将无法访问。

帮帮我!谢谢!

最佳答案

您应该将委托(delegate)从 VC1 传递到 VC2,然后只需调用委托(delegate)方法进行更新。

在此处发送对 VC2 的引用。

@IBAction func chooseLabelTextBtnPressed(sender: AnyObject) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("VC2") as! VC2
vc.delegate = self
self.presentViewController(vc, animated: true, completion: nil)
}

在 VC2 中调用 self.dismissViewControllerAnimated(true, completion: nil) 之前,只需调用 delegate.someMethod(someValue)

还要确保您的委托(delegate)是弱引用。

关于ios - Swift:在 dismissViewControllerAnimated 上将字符串值从 VC2 传递到 VC1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35947520/

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