【问题标题】:Pass value once Popover table view is dismissed in SWIFT在 SWIFT 中关闭 Popover 表视图后传递值
【发布时间】:2018-07-06 09:14:16
【问题描述】:

我有一个如下的故事板:

单击第一个字段(选择表单)时,第二个视图将显示为弹出框。我在弹出框表格视图中有一组值作为表格单元格。 因此,当我单击 tableview 中的任何单元格时,一旦禁用弹出框,我需要在第二个文本框(NewFormName)中使用该值。

我在 MainViewController 中获得了价值。但无法使用它来更改文本框的值。

这是我的弹出框 didselectanyrow 代码:

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    var dict = FormList[(indexPath as NSIndexPath).row]

    let formname:String = dict.form_name!;

    /*created an instance called 
   'MainViewControllerInstance' of MainViewController earlier*/

    MainViewControllerInstance.SecondTextBox.text = formname
    self.dismiss(animated: true, completion: nil)

}

这显示一个错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

有什么解决办法吗?一旦弹出框被解除,我需要将弹出框表格单元的选定值添加到第二个文本框。

【问题讨论】:

  • 使用闭包作为变量并获取值
  • 我认为你不应该假设 dict.form_name 不为零。
  • 你不能MainViewControllerInstance.SecondTextBox.text 直接在SecondVC中取变量赋值
  • 尝试检查 FormList 本身是否为 nil。
  • 值实际上不是零。我可以在主视图控制器的控制台中打印值。但无法在 TextBox.text 中使用它

标签: ios swift xcode swift4


【解决方案1】:

在你的PopoverViewController:

var delegate: MainViewController?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    var dict = FormList[(indexPath as NSIndexPath).row]
    let formname: String? = dict.form_name
    delegate?.updateTextBox(with: formname)
    self.dismiss(animated: true, completion: nil)

}

在你的MainViewController

func updateTextBox(with string: String?) {
    if string != nil {
        self.SecondTextBox.text = string!
    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "popoverSegue" {
            let popoverViewController = segue.destinationViewController as! PopoverViewController
            popoverViewController.delegate = self
        }
    }

【讨论】:

  • 享受编码! :)
【解决方案2】:

使用委托或闭包将值传递回最后一个对象

【讨论】:

  • 你的意思是这样使用吗?我是这样贴的,让delegate = UIApplication.shared.delegate 为! MainViewController 并像这样使用:delegate.textBox.text = "My Text" 但没有用。线程/错误
猜你喜欢
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多