用swift5写一个注册登陆页面
时间: 2023-07-01 11:05:51 浏览: 93
以下是一个简单的注册登录页面的 Swift 5 代码示例:
```swift
import UIKit
class ViewController: UIViewController {
// 注册页面 UI 控件
@IBOutlet weak var registerUsernameTextField: UITextField!
@IBOutlet weak var registerPasswordTextField: UITextField!
@IBOutlet weak var registerConfirmPasswordTextField: UITextField!
@IBOutlet weak var registerButton: UIButton!
// 登录页面 UI 控件
@IBOutlet weak var loginUsernameTextField: UITextField!
@IBOutlet weak var loginPasswordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// 隐藏键盘
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
view.addGestureRecognizer(tapGesture)
}
@objc func hideKeyboard() {
view.endEditing(true)
}
@IBAction func registerButtonTapped(_ sender: Any) {
guard let username = registerUsernameTextField.text, !username.isEmpty else {
showAlert(message: "请输入用户名")
return
}
guard let password = registerPasswordTextField.text, !password.isEmpty else {
showAlert(message: "请输入密码")
return
}
guard let confirmPassword = registerConfirmPasswordTextField.text, !confirmPassword.isEmpty else {
showAlert(message: "请确认密码")
return
}
if password != confirmPassword {
showAlert(message: "两次输入的密码不一致")
return
}
// 在此处添加注册代码
showAlert(message: "注册成功")
}
@IBAction func loginButtonTapped(_ sender: Any) {
guard let username = loginUsernameTextField.text, !username.isEmpty else {
showAlert(message: "请输入用户名")
return
}
guard let password = loginPasswordTextField.text, !password.isEmpty else {
showAlert(message: "请输入密码")
return
}
// 在此处添加登录代码
showAlert(message: "登录成功")
}
func showAlert(message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
```
在 Storyboard 中,可以将上述代码中的 UI 控件拖拽到相应的视图控制器中。注册按钮和登录按钮可以分别绑定到 `registerButtonTapped` 和 `loginButtonTapped` 方法上。同时,还需要将 `hideKeyboard` 方法绑定到视图上以实现点击空白处隐藏键盘的功能。
阅读全文