我有兩個viewcontroller類。 MainViewController有一個UITextField,SecondViewController有一個UILabel。我想從UILabe中的UITextField打印文本。請告訴我以編程方式執行此操作的最佳方式。下面是我的代碼:以編程方式在視圖控制器之間傳遞數據Swift
// AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
窗口=一個UIWindow(幀:UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = MainViewController()
window?.backgroundColor = UIColor.yellow
application.statusBarStyle = .lightContent
return true
}
}
// MainViewController類
import UIKit
class MainViewController: UIViewController {
let label = UILabel()
let textField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.gray
setupLabel()
setupTextField()
setupButton()
}
func setupLabel() {
label.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
label.text = "welcome to my world"
label.textColor = UIColor.yellow
label.font = UIFont.boldSystemFont(ofSize: 25)
label.textAlignment = .center
label.layer.borderWidth = 2
label.layer.borderColor = UIColor.yellow.cgColor
label.layer.cornerRadius = 5
view.addSubview(label)
}
func setupTextField() {
textField.frame = CGRect(x: 10, y: 200, width: self.view.frame.size.width - 20, height: 60)
textField.placeholder = "text here"
textField.textAlignment = .center
textField.font = UIFont.systemFont(ofSize: 25)
textField.layer.borderWidth = 2
textField.layer.borderColor = UIColor.yellow.cgColor
textField.layer.cornerRadius = 5
view.addSubview(textField)
}
func setupButton() {
let button = UIButton()
button.frame = CGRect(x: 50, y: 300, width: self.view.frame.size.width - 100, height: 60)
button.setTitle("Enter", for: .normal)
button.setTitleColor(UIColor.yellow, for: .normal)
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.yellow.cgColor
button.layer.cornerRadius = 5
button.addTarget(self, action: #selector(buttonTarget), for: .touchUpInside)
view.addSubview(button)
}
func buttonTarget() {
// i missed here maybe
}
}
// SecondViewController類
import UIKit
class SecondViewController: UIViewController {
let secondLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
setupLabelSecond()
}
func setupLabelSecond() {
secondLabel.frame = CGRect(x: 40, y: 80, width: 300, height: 60)
secondLabel.text = "this is Second Page"
secondLabel.textColor = UIColor.yellow
secondLabel.font = UIFont.boldSystemFont(ofSize: 25)
secondLabel.textAlignment = .center
secondLabel.layer.borderWidth = 2
secondLabel.layer.borderColor = UIColor.yellow.cgColor
secondLabel.layer.cornerRadius = 5
view.addSubview(secondLabel)
}
}
@vadian你能回答他請或一些提示 –
@vadian我試圖做沒有故事板。 –
也有沒有故事板的建議。 – vadian