我的视图有两个文本字段和一个按钮。
@IBOutlet var inputURL: UITextField!
@IBOutlet var inputName: UITextField!
@IBAction func submitUrlButton(sender: AnyObject) {
}
和第二个包含两个变量的视图:
var submittedURL = ""
var submittedName = ""
println("Name \(submittedName)")
println("URL \(submittedURL)")
在Swift中如何传递在两个文本字段中输入的值并将它们分配给第二个视图中的那些变量?
由于
为此编辑:
import UIKit
class ViewController: UIViewController {
@IBOutlet var inputURL: UITextField!
@IBAction func submitBtn(sender: AnyObject) {
performSegueWithIdentifier("submissionSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Create a new variable to store the instance of the next view controller
let destinationVC = segue.destinationViewController as BrandsViewController
destinationVC.submittedURL.text = inputURL.text
}
}
答案 0 :(得分:4)
您可以使用prepareForSegue方法。
在第一个视图(segue来自的视图)中,编写以下代码:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Create a new variable to store the instance of the next view controller
let destinationVC = segue.destinationViewController as CustomViewController
destinationVC.submittedURL = inputURL.text
destinationVC.submittedName = inputName.text
}
这里CustomViewController是segue将要访问的UIViewController的自定义类。
要在按钮@IBAction中以编程方式执行segue,请执行以下操作:
@IBAction func buttonWasClicked(sender: AnyObject) {
performSegueWithIdentifier("submissionSegue", sender: self)
}
答案 1 :(得分:1)
由于您的视图控制器与segue链接,您可以覆盖第一个视图控制器中的prepareForSegue方法并通过这样做传递数据
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "secondViewController") { // here secondViewController is your segue identifier
var secondViewController = segue.destinationViewController as SecondViewController // where SecondViewController is the name of your second view controller class
secondViewController.submittedURL = inputURL.text
secondViewController.submittedName = inputName.text
}
}
要在按钮操作中执行Segue,请使用perfromSegueWithIdentifier方法
@IBAction func submitUrlButton(sender: AnyObject) {
//replace identifier with your identifier from storyboard
self.performSegueWithIdentifier("secondViewController", sender: self)
}
答案 2 :(得分:0)
The simplest way of accessing values globally not neccessary to pass with segue
第一个视图控制器
import UIKit
var submittedURL:NSString? // declare them here
var submittedName:NSString? // Now these two variables are accessible globally
class YourViewController : UIViewController
{
@IBOutlet var inputURL: UITextField!
@IBOutlet var inputName: UITextField!
@IBAction func submitUrlButton(sender: AnyObject) {
if inputURL.text == "" && inputName.text == ""
{
//Show an alert here etc
}
else {
self.submittedURL.text = inputURL.text
self.submittedName.text = inputName.text
}
}
}
SecondView控制器
import UIKit
class SecondviewController: UIViewController
{
//inside viewDidload
println(submittedURL)
println(submittedName)
}