Để 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

Custom Alert nâng cao (Custom View)
Nếu cần UI hoàn toàn tùy chỉnh (custom layout, animation, textfield...):
- Tạo
UIViewControllerriêng với view custom. - Set
modalPresentationStyle = .overCurrentContext(hoặc .overFullScreen). modalTransitionStyle = .crossDissolve.- Present như bình thường.
let customAlert = CustomAlertViewController()
customAlert.modalPresentationStyle = .overCurrentContext
customAlert.modalTransitionStyle = .crossDissolve
present(customAlert, animated: true)
Lưu ý
UIAlertControllerkhông cho custom view nội dung (chỉ title, message, actions, textFields).- Trên iPad,
.actionSheetbắt buộc setpopoverPresentationController.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
UITextFieldvào alert:alert.addTextField { $0.placeholder = "Nhập tên" }.