我正在尝试将数据从ViewController(我们称之为ViewControllerA)传递给ViewControllerB。我以编程方式创建了ViewControllers,因此我根本不使用故事板。 我想在ViewControllerB中的UILabel中显示用户在ViewControllerA中的UITextField中输入的内容。有什么办法可以通过编程方式完成吗? 我只是一个初学者,所以给我一个你知道的最简单的解决方案,因为它是最容易掌握的。谢谢!
思考是代码的示例
ViewControllerA:
import UIKit
class ViewControllerA: UIViewController {
let player1: UITextField = {
let p1 = UITextField()
p1.placeholder = "Player"
return p1
}()
let goButton: UIButton = {
let go = UIButton(type: .system)
go.setTitle("Go!", for: .normal)
go.addTarget(self, action: #selector(Go), for: .touchUpInside)
return go
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(player1)
view.addSubview(goButton)
}
func Go() {
let viewB = ViewControllerB()
present(viewB, animated: true, completion: nil)
}
}
ViewControllerB:
import UIKit
class ViewControllerB: UIViewController {
let topLabel: UILabel = {
let tl = UILabel()
tl.textColor = UIColor.white
return tl
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(topLabel)
}
}
(当用户按下goButton时,我希望ViewControllerB中的topLabel.text等于ViewControllerA的player1.text)