To set up auto layout for a username field, password field, login button, and forgot credential button programmatically in Swift, you can use the NSLayoutConstraint
class to define the relationships between these UI elements. Here’s an example of how you can do this:
import UIKit
class YourViewController: UIViewController {
// Create UI elements
let usernameField: UITextField = {
let textField = UITextField()
textField.placeholder = "Username"
textField.borderStyle = .roundedRect
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
let passwordField: UITextField = {
let textField = UITextField()
textField.placeholder = "Password"
textField.borderStyle = .roundedRect
textField.isSecureTextEntry = true
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
let loginButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Login", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
let forgotButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Forgot Credentials", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
// Add UI elements to the view
view.addSubview(usernameField)
view.addSubview(passwordField)
view.addSubview(loginButton)
view.addSubview(forgotButton)
// Set up auto layout constraints
NSLayoutConstraint.activate([
// Username Field
usernameField.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),
usernameField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
usernameField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
// Password Field
passwordField.topAnchor.constraint(equalTo: usernameField.bottomAnchor, constant: 20),
passwordField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
passwordField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
// Login Button
loginButton.topAnchor.constraint(equalTo: passwordField.bottomAnchor, constant: 20),
loginButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
loginButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
// Forgot Button
forgotButton.topAnchor.constraint(equalTo: loginButton.bottomAnchor, constant: 20),
forgotButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
forgotButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
])
}
}
This example creates and configures UITextField
and UIButton
instances, adds them to the view, and then sets up constraints using NSLayoutConstraint
to define their positions and relationships. Adjust the constraints according to your layout preferences.