import UIKit
class ViewController: UIViewController {
@IBOutlet weak var username: UITextField!
@IBAction func loginPressed(_ sender: Any) {
print("Username entered is \(username.text)")
let displayViewController = storyboard?.instantiateViewController(withIdentifier: "DisplayViewController") as! DisplayViewController
displayViewController.usernameEntered = username.text
self.navigationController?.pushViewController(displayViewController, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
我试图传输这些数据"用户名"到另一个视图控制器。我的大部分工作正常,但displayViewController.usernameEntered = username.text
以下是我的其他视图控制器的代码:
import UIKit
class DisplayViewController: UIViewController {
var usernameEntered:String?
@IBOutlet weak var usernameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let usernameToDisplay = usernameEntered
{
self.usernameLabel.text = usernameToDisplay
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
对于为什么会发生这种情况的任何见解将不胜感激!
答案 0 :(得分:2)
检查username.text
不应该是nil
&安培;确保您已从故事板中连接usernameEntered
标签插座。