【问题标题】:Value not passing between viewControllers值不在视图控制器之间传递
【发布时间】:2019-02-17 22:03:49
【问题描述】:

努力让我的 viewControllers 将值从主 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"
}

}

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

【问题讨论】:

  • 删除let vc = TimesTablesViewController(nibName: "TimesTablesViewController", bundle: nil); vc.passedValue = "xx"并实现prepareForSegue传递值。

标签: swift xcode uiviewcontroller


【解决方案1】:

替换

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

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

或者(如果当前的vc在一个naigation里面)

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

【讨论】:

  • 这并不完全正确。他没有正确实例化视图控制器,所以他无法推送或呈现它。
  • 从帖子中的哪些信息中您认为这是故事板?如果是这样,这已经回答了
  • 我的错。现在有点晚了,我的大脑可能太累了。对不起
  • 下面的方法解决了我的问题。感谢您的帮助!
【解决方案2】:

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

如果您真的在使用故事板,请简化您的 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方法之间的连接,在右侧面板的“Connections Inspector”选项卡上;和
  • control - 从之前连接到butClick(_:) 的按钮拖动到TimesTablesViewController 的场景。

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

【讨论】:

  • 谢谢,这行得通。当我从按钮中获取文本时,我仍然认为我需要按钮事件。
猜你喜欢
  • 1970-01-01
  • 2018-07-03
  • 2017-01-01
  • 2019-08-12
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 2018-06-22
  • 2012-04-20
相关资源
最近更新 更多