先再先來做新增功能了
指令:
設計一個左側navbtn 新增人員的btn 使用"+"當標題 使用alert 同時輸入email與name
程式:
// 設置"+"按鈕
private func setupAddButton() {
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonTapped))
navigationItem.leftBarButtonItem = addButton
}
// "+"按鈕點擊事件
@objc private func addButtonTapped() {
showAddPersonAlert()
}
// 顯示新增人員的警告框
private func showAddPersonAlert() {
let alertController = UIAlertController(title: "新增人員", message: "請輸入人員資料", preferredStyle: .alert)
// 添加姓名輸入欄位
alertController.addTextField { textField in
textField.placeholder = "姓名"
}
// 添加電子郵件輸入欄位
alertController.addTextField { textField in
textField.placeholder = "電子郵件"
textField.keyboardType = .emailAddress
}
// 添加取消按鈕
let cancelAction = UIAlertAction(title: "取消", style: .cancel)
// 添加確認按鈕
let confirmAction = UIAlertAction(title: "確認", style: .default) { [weak self] _ in
guard let nameTextField = alertController.textFields?[0],
let emailTextField = alertController.textFields?[1],
let name = nameTextField.text, !name.isEmpty else {
// 如果姓名為空,顯示錯誤訊息
self?.showErrorAlert(message: "姓名不能為空")
return
}
// 獲取電子郵件(可以為空)
let email = emailTextField.text?.isEmpty == true ? nil : emailTextField.text
}
alertController.addAction(cancelAction)
alertController.addAction(confirmAction)
present(alertController, animated: true)
}
// 顯示成功訊息
private func showSuccessAlert(message: String) {
let alertController = UIAlertController(title: "成功", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "確定", style: .default)
alertController.addAction(okAction)
present(alertController, animated: true)
}
// 顯示錯誤訊息
private func showErrorAlert(message: String) {
let alertController = UIAlertController(title: "錯誤", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "確定", style: .default)
alertController.addAction(okAction)
present(alertController, animated: true)
}