[英]Can a toolbar be added to a UIAlertController, as well as buttons to the rows using Swift?
[英]How to make UIAlertController compatible for iPad as well as iPhones using Swift
我創建了一個圖像選擇器用戶界面,當用戶單擊按鈕時我想在其中進行選擇,我使用 UIAlertController 完成了它,當我在 iPhone 中測試它時它工作完美但是,當我在 iPad 中測試它然后在單擊按鈕后,該應用程序崩潰了。
如何使 UIAlertController 也與 iPad 兼容?
分機 UIViewController
extension UIViewController{
public func addAlertForiPad(alert: UIAlertController) {
if let alertController = alert.popoverPresentationController {
alertController.sourceView = view
alertController.sourceRect = CGRect(x: view.bounds.midX, y: view.bounds.midY, width: 0, height: 0)
alertController.permittedArrowDirections = []
}
}
}
用法
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet)
if UIDevice.current.userInterfaceIdiom == .pad {
addAlertForiPad(alert: alertController)
}
alertController.popoverPresentationController?.sourceView = view
alertController.addAction(UIAlertAction(title: "Approve", style: .default , handler:{ (UIAlertAction)in
print("User click Approve button")
}))
alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler:{ (UIAlertAction)in
print("User click Dismiss button")
}))
present(alertController, animated: true, completion: nil)
在 iPad 上,必須相對於其他一些 controller 顯示 uialertcontroller,因為您不能只在“屏幕上的任何位置”顯示它。
我們可以用
let ac = UIAlertController(title: nil, message: nil, preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet)
完整代碼在 swift
@IBAction func pickBTN(_ sender: UIButton) {
let ac = UIAlertController(title: nil, message: nil, preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet)
ac.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { action in
self.gallery()
}))
ac.addAction(UIAlertAction(title: "Camera", style: .default, handler: { action in
self.camera()
}))
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
}))
present(ac, animated: true)
}
上面代碼中使用的功能(用於相機和圖庫)
func gallery (){
imagePicker.allowsEditing = false
imagePicker.sourceType = .savedPhotosAlbum
present(imagePicker, animated: true, completion: nil)
}
func camera (){
imagePicker.allowsEditing = false
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.