值不在 viewController 之间传递

Value not passing between viewControllers

努力让我的 viewController 将值从主 viewController 发送到第二个。我希望它在单击按钮时发生,我将从按钮中获取值并将其传递给新表单。但它就是行不通。

主要代码 ViewController

class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
}

@IBAction func butClick(_ sender: UIButton) {
    NSLog("Button Pressed : %@",[sender .currentTitle])
    //var tt = [sender .currentTitle]
    // Create the view controller
    let vc = TimesTablesViewController(nibName: "TimesTablesViewController", bundle: nil)
    vc.passedValue = "xx"
    self.performSegue(withIdentifier: "pushSegue", sender: nil)

}
}

第二个 viewController 的代码称为 TimesTablesViewController:

class TimesTablesViewController: UIViewController {

@IBOutlet weak var titleLabel: UILabel!

var passedValue:String = ""

override func viewDidLoad() {
    super.viewDidLoad()
    titleLabel?.text = "\(passedValue) Times Table"
}

}

我已经按照教程进行操作,但似乎无法解决问题!感谢您的帮助!

替换

self.performSegue(withIdentifier: "pushSegue", sender: nil)

self.present(vc,animated:true,completion:nil)

或(如果当前 vc 在航海内)

self.navigationController?.pushViewController(vc,animated:true)

使用

self.performSegue(withIdentifier: "pushSegue", sender: nil)

适合故事板而不是 xibs,如果这是你的情况,那么你只需要在按钮操作中使用上面的行,并在源代码中实现此方法 vc

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "pushSegue"  {
        if let nextViewController = segue.destination as? TimesTablesViewController{
                nextViewController.passedValue = "xx"  
        }
    }
}

我假设新的视图控制器出现了,但您根本看不到数据。如果是这样,您显然正在使用故事板。 TimesTablesViewController(nibName:bundle:) 仅在您使用 XIB/NIBs 并手动呈现新视图控制器时才有效。

如果您真的在使用故事板,请简化您的 butClick 方法:

@IBAction func butClick(_ sender: UIButton) {
    NSLog("Button Pressed")
    performSegue(withIdentifier: "pushSegue", sender: self)
}

但执行 prepare(for:sender:):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? TimesTablesViewController {
        destination.passedValue = "xx"
    }
}

假设以上解决了您的问题,我可能会建议进一步简化。值得注意的是,如果你的 butClick(_:) 方法真的只调用 performSegue,你可以在没有任何 @IBAction 方法的情况下进入下一个场景:

  • 完全删除 butClick(_:)
  • 删除按钮和IB中butClick方法之间的连接,在右侧面板的“连接检查器”选项卡上;和
  • 控制-从之前连接到butClick(_:)的按钮拖到TimesTablesViewController的场景。

这将进一步简化您的代码。