Computer >> Máy Tính >  >> Lập trình >> IOS

Cách tạo Hộp thoại tùy chỉnh trên Ứng dụng iOS bằng Swift?


Để tạo hộp thoại nhanh chóng, chúng tôi sẽ sử dụng UIAlertController, một phần quan trọng của UIKit. Chúng tôi sẽ thực hiện việc này với sự trợ giúp của ứng dụng iOS và một dự án mẫu.

Trước hết, chúng tôi sẽ tạo một dự án trống, sau đó bên trong bộ điều khiển chế độ xem mặc định của nó, chúng tôi sẽ thực hiện các thao tác sau.

Chúng tôi sẽ tạo một đối tượng UIAlertController.

let alert = UIAlertController.init(title: title, message: description, preferredStyle: .alert)

Chúng tôi sẽ tạo một hành động

let okAction = UIAlertAction.init(title: "Ok", style: .default) { _ in
   print("You tapped ok")
   //custom action here.
}

Chúng tôi sẽ thêm hành động vào cảnh báo và hiển thị nó

alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)

Bây giờ chúng ta sẽ chuyển nó thành một hàm -

func createAlert(withTitle title:String,andDescription description: String) {
   let alert = UIAlertController.init(title: title, message: description, preferredStyle: .alert)
   let okAction = UIAlertAction.init(title: "Ok", style: .default) {
       _ in print("You tapped ok")
      //custom action here.
   }
   alert.addAction(okAction)
   self.present(alert, animated: true, completion: nil)
}

Bây giờ chúng ta sẽ gọi hàm trong phương thức viewWillLayoutSubviews của chúng ta và đây là cách nó trông như thế nào khi chúng ta chạy hàm này trên một thiết bị.

override func viewWillLayoutSubviews() {
   self.createAlert(withTitle: "This is an alert", andDescription: "Enter your description here.")
}

Điều này tạo ra kết quả như hình dưới đây.

Cách tạo Hộp thoại tùy chỉnh trên Ứng dụng iOS bằng Swift?