Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách tạo Custom Dialog (Alert) trên iOS App bằng Swift

Để tạo hộp thoại (dialog/alert) tùy chỉnh trong iOS, dùng UIAlertController (style .alert hoặc .actionSheet). Đây là cách chuẩn, không cần thư viện thứ 3.

Alert cơ bản (Style .alert)


func showAlert(title: String, message: String) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    
    let okAction = UIAlertAction(title: "OK", style: .default) { _ in
        print("User tapped OK")
        // Xử lý logic ở đây
    }
    
    let cancelAction = UIAlertAction(title: "Hủy", style: .cancel) { _ in
        print("User tapped Cancel")
    }
    
    alert.addAction(okAction)
    alert.addAction(cancelAction)
    
    present(alert, animated: true)
}

Action Sheet (Style .actionSheet) - iPad cần sourceView


func showActionSheet() {
    let alert = UIAlertController(title: "Chọn hành động", message: nil, preferredStyle: .actionSheet)
    
    alert.addAction(UIAlertAction(title: "Chụp ảnh", style: .default) { _ in
        self.openCamera()
    })
    alert.addAction(UIAlertAction(title: "Chọn từ thư viện", style: .default) { _ in
        self.openPhotoLibrary()
    })
    alert.addAction(UIAlertAction(title: "Hủy", style: .cancel))
    
    // iPad: BẮT BUỘC set popoverPresentationController
    if let popover = alert.popoverPresentationController {
        popover.sourceView = self.view
        popover.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
        popover.permittedArrowDirections = []
    }
    
    present(alert, animated: true)
}

Kết quả Alert

Cách tạo Custom Dialog (Alert) trên iOS App bằng Swift

Custom Alert nâng cao (Custom View)

Nếu cần UI hoàn toàn tùy chỉnh (custom layout, animation, textfield...):

  1. Tạo UIViewController riêng với view custom.
  2. Set modalPresentationStyle = .overCurrentContext (hoặc .overFullScreen).
  3. modalTransitionStyle = .crossDissolve.
  4. Present như bình thường.

let customAlert = CustomAlertViewController()
customAlert.modalPresentationStyle = .overCurrentContext
customAlert.modalTransitionStyle = .crossDissolve
present(customAlert, animated: true)

Lưu ý

  • UIAlertController không cho custom view nội dung (chỉ title, message, actions, textFields).
  • Trên iPad, .actionSheet bắt buộc set popoverPresentationController.sourceView否则 crash.
  • Style action: .default (mặc định), .cancel (in đậm, dismiss), .destructive (màu đỏ, xóa/hủy dữ liệu).
  • Có thể thêm UITextField vào alert: alert.addTextField { $0.placeholder = "Nhập tên" }.