Swift 值不在ViewController之间传递
努力让我的viewController将值从主viewController发送到第二个。我希望它在点击按钮时发生,我将从按钮获取值并将其传递给新表单。但它就是不起作用 主视图控制器的代码Swift 值不在ViewController之间传递,swift,xcode,uiviewcontroller,Swift,Xcode,Uiviewcontroller,努力让我的viewController将值从主viewController发送到第二个。我希望它在点击按钮时发生,我将从按钮获取值并将其传递给新表单。但它就是不起作用 主视图控制器的代码 class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func butClick(_ sender: UIButton) { NSLog("B
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)
}
}
第二个名为TimeTablesViewController的viewController的代码:
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)
与
或者(如果当前vc位于导航内)
使用
self.performSegue(withIdentifier: "pushSegue", sender: nil)
适用于故事板而不是XIB,如果这是您的情况,那么您只需要在按钮操作中使用上面的行,并在源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并手动显示新的视图控制器时有效
如果您真的在使用故事板,请简化您的,但单击方法:
@IBAction func butClick(_ sender: UIButton) {
NSLog("Button Pressed")
performSegue(withIdentifier: "pushSegue", sender: self)
}
但实施准备(针对:发件人:)
:
假设以上解决了您的问题,我可能会建议进一步简化。值得注意的是,如果您的butClick(:)
方法实际上只调用performsgue
,则您可以转到下一个场景,而无需任何@IBAction
方法:
- 删除
,但完全单击(:)
李>
- 移除按钮与
之间的连接,但单击右侧面板“Connections Inspector”选项卡上IB中的方法;及
- 控件从以前连接到
的按钮拖动,但单击(:)
到TimeTablesViewController
的场景
这将进一步简化您的代码。Deletelet vc=timestableviewcontroller(nibName:“timestableviewcontroller”,bundle:nil);vc.passedValue=“xx”
并实现prepareforsgue
来传递值。这并不完全正确。他没有正确实例化视图控制器,因此他无法推送或呈现它。从帖子中的哪些信息,您认为它是情节提要?如果是这样的话,我的回答已经很糟糕了。现在有点晚了,我的大脑可能太累了。对不起,下面的方法解决了我的问题。谢谢你的帮助!谢谢,这很有效。当我从按钮获取文本时,我仍然认为我需要按钮事件。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pushSegue" {
if let nextViewController = segue.destination as? TimesTablesViewController{
nextViewController.passedValue = "xx"
}
}
}
@IBAction func butClick(_ sender: UIButton) {
NSLog("Button Pressed")
performSegue(withIdentifier: "pushSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? TimesTablesViewController {
destination.passedValue = "xx"
}
}