I have two viewcontroller classes. MainViewController has a UITextField and SecondViewController has a UILabel. I want to print the text from the UITextField in the UILabe. Please tell me the best way to do this programmatically. Below is my code:
// AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = MainViewController()
window?.backgroundColor = UIColor.yellow
application.statusBarStyle = .lightContent
return true
}
}
// MainViewController Class
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 class
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)
}
}

