【问题标题】:How to push data through a navigation View Controller如何通过导航视图控制器推送数据
【发布时间】:2017-05-20 16:22:53
【问题描述】:

我有一个针对此函数的提交 UIButton,并且我有一个我想传递给下一个视图控制器的 textField。因此,用户将在 textField 中输入任何内容,一旦用户点击提交按钮,文本字段内的字符串将被传递到下一个视图控制器的 UILabel。

    func submitTapped() {
        let secondViewController = SecondViewController(nibName: nil, bundle: nil)
        navigationController?.pushViewController(secondViewController, animated: true)

        print("Button tapped")
    }
}

如何通过第二个控制器推送该字符串?另外,我尝试过使用 prepareForSegue,但我认为这与 segue 无关,因为我们不是通过 segue 转换屏幕,而是通过导航控制器进行转换,对吗?

谢谢!

【问题讨论】:

标签: ios swift navigation


【解决方案1】:

在 SecondViewController 中,在创建对象的同时创建一个变量并赋值。检查以下示例:

class SecondViewController {
 var dataString: String?
}

如下传递数据:

func submitTapped() {
        let secondViewController = SecondViewController(nibName: nil, bundle: nil)
        secondViewController.dataString = textField.text!
        navigationController?.pushViewController(secondViewController, animated: true)
        print("Button tapped")
    }
}

【讨论】:

  • 谢谢!但这不会在两个类之间创建紧密耦合吗?还有其他方法可以实现吗?
【解决方案2】:

在 YourSecondViewController 中,声明一个变量。

class YourSecondViewController {
     var strData: String?
    }

使用以下代码传递数据:

func submitTapped() {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let objSecond = storyboard.instantiateViewController(withIdentifier: "YourSecondViewControllerID")
    objSecond.strData = yourTextField.text!
    self.navigationController?.pushViewController(objSecond, animated: true)
}

【讨论】:

    猜你喜欢
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    相关资源
    最近更新 更多