import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
let nameTextField = UITextField()
let nameLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
nameTextField.placeholder = "Enter your name"
nameTextField.borderStyle = .roundedRect
nameTextField.translatesAutoresizingMaskIntoConstraints = false
nameTextField.delegate = self
view.addSubview(nameTextField)
nameLabel.text = "Your name is:"
nameLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(nameLabel)
NSLayoutConstraint.activate([
nameTextField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
nameTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
nameTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
nameLabel.topAnchor.constraint(equalTo: nameTextField.bottomAnchor, constant: 20),
nameLabel.leadingAnchor.constraint(equalTo: nameTextField.leadingAnchor),
nameLabel.trailingAnchor.constraint(equalTo: nameTextField.trailingAnchor)
])
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let currentText = textField.text as NSString? {
let updatedText = currentText.replacingCharacters(in: range, with: string)
nameLabel.text = "Your name is: " + updatedText
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}We create a UITextField with a placeholder and a rounded border. We add a UILabel below it to show the typed name. Both views use Auto Layout constraints for proper positioning and responsiveness. The ViewController conforms to UITextFieldDelegate to update the label text as the user types and to dismiss the keyboard when the return key is pressed.