我是一個新的程序員,並在控制器之間傳遞數據掙扎,我知道這些問題在這些論壇中被問到,但上傳的代碼比我的複雜得多,我很難理解它會上傳我寫的幾行。我想讓兩名玩家在我的應用中輸入他們的名字,然後點擊開始遊戲。當開始遊戲按鈕被按下時,它將它們帶到一個新的視圖控制器,它的名字就像這樣Joe Bloggs vs John Doe,我可以實現這個如果我讓我的變量是全局的,但我的理解是這是不好的做法,所以當我嘗試編寫相同的代碼,保持視圖控制器內的變量它每次都通過零,我不確定我做錯了什麼?這是我的幾行代碼,我希望有人能回答我做錯了什麼?視圖控制器之間傳遞數據產生零
的ViewController:
import UIKit
class ViewController: UIViewController {
var playerOneName: String!
var playerTwoName: String!
@IBOutlet weak var playerOneTextField: UITextField!
@IBOutlet weak var playerTwoTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func startGameButton(_ sender: Any) {
playerOneName = playerOneTextField.text!
playerTwoName = playerTwoTextField.text!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
let destinationVC = segue.destination as! GameViewController
destinationVC.playerOne.text = playerOneName
destinationVC.playerTwo.text = playerTwoName
}
}
}
GameViewController:
import UIKit
class GameViewController: UIViewController {
@IBOutlet weak var playerOne: UILabel!
@IBOutlet weak var playerTwo: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
你檢查,如果文本字段被正確地映射到變量?在按鈕回調之前調用'prepare(for:sender:)'會怎麼樣? – gskbyte
因爲當您執行destinationVC.playerOne.text = playerOneName時,'playerOne'是'nil'。換句話說,'IBOulet'尚未加載。創建一個將保存'playerOneName'值的'String'屬性。在'viewDidLoad()'設置'playerOne.text'。 – Larme
在Objective-C中,但原因是一樣的:https://stackoverflow.com/questions/18137073/set-uitextfield-text-property-in-prepareforsegue或https://stackoverflow.com/questions/9576177/how-可以-I-設定的值對的一-的UILabel-以下-A-SEGUE – Larme