Chatgpt
- Create RegisterViewController.swift
ปกด UI และตรรกะที่เกี่ยวข้องกับการลงทะเบียนผู้ใช้งานใหม่ เช่น การกรอกชื่อผู้ใช้, รหัสผ่าน, และการยืนยันข้อมูล
import UIKit
class RegisterViewController: UIViewController {
// UI Elements
let usernameField = UITextField()
let passwordField = UITextField()
let registerButton = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "Register"
setupUI()
}
func setupUI() {
// Configure Username Field
usernameField.placeholder = "Enter username"
usernameField.borderStyle = .roundedRect
usernameField.translatesAutoresizingMaskIntoConstraints = false
// Configure Password Field
passwordField.placeholder = "Enter password"
passwordField.borderStyle = .roundedRect
passwordField.isSecureTextEntry = true
passwordField.translatesAutoresizingMaskIntoConstraints = false
// Configure Register Button
registerButton.setTitle("Register", for: .normal)
registerButton.addTarget(self, action: #selector(registerTapped), for: .touchUpInside)
registerButton.translatesAutoresizingMaskIntoConstraints = false
// Add Subviews
view.addSubview(usernameField)
view.addSubview(passwordField)
view.addSubview(registerButton)
// Layout Constraints
NSLayoutConstraint.activate([
usernameField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
usernameField.topAnchor.constraint(equalTo: view.topAnchor, constant: 200),
usernameField.widthAnchor.constraint(equalToConstant: 250),
passwordField.centerXAnchor.constraint(equalTo: view.centerXAnchor),
passwordField.topAnchor.constraint(equalTo: usernameField.bottomAnchor, constant: 20),
passwordField.widthAnchor.constraint(equalToConstant: 250),
registerButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
registerButton.topAnchor.constraint(equalTo: passwordField.bottomAnchor, constant: 20),
registerButton.widthAnchor.constraint(equalToConstant: 100)
])
}
@objc func registerTapped() {
let username = usernameField.text ?? ""
let password = passwordField.text ?? ""
// Basic validation
if username.isEmpty || password.isEmpty {
showAlert(message: "Please enter both username and password.")
return
}
// Save credentials to UserDefaults (for demo purposes)
UserDefaults.standard.set(username, forKey: "username")
UserDefaults.standard.set(password, forKey: "password")
showAlert(message: "Registration Successful!")
}
func showAlert(message: String) {
let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
2. Create LoginViewController.swift
04 Login Register presentViewController
The easiest way to build a Login,
Create Modern App Button in 60 Seconds (Swift)
Swift Tutorial – Custom UIButton Class (Reusable)
