UIAlertControllerを使ってみる
とりあえず画面にボタンを追加します
ボタン押下時にUIAlertControllerを表示するよう変更
@IBAction func btnClick(_ sender: UIButton) { let ac = UIAlertController(title:"Title", message: "Message", preferredStyle: UIAlertControllerStyle.alert) let aDef = UIAlertAction(title: "default", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in print("Default!") }) let aDes = UIAlertAction(title: "destructive", style: UIAlertActionStyle.destructive, handler: { (action: UIAlertAction!) in print("Default!") }) let aCan = UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel, handler: { (action: UIAlertAction!) in print("Cancel!") }) ac.addAction(aDef) ac.addAction(aDes) ac.addAction(aCan) self.present(ac, animated: true, completion:popoverPresentationController) }
表示できました。
addActionを2つに減らすと表示されるボタンのスタイルが少し変わります。
できました。
下からの表示に変更します。
UIAlertControllerStyle.alert を UIAlertControllerStyle.actionSheet に変更すれば下からの表示になります。
@IBAction func btnClick(_ sender: UIButton) { let ac = UIAlertController(title:"Title", message: "Message", preferredStyle: UIAlertControllerStyle.actionSheet) let aDef = UIAlertAction(title: "default", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in print("Default!") }) let aDes = UIAlertAction(title: "destructive", style: UIAlertActionStyle.destructive, handler: { (action: UIAlertAction!) in print("Default!") }) let aCan = UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel, handler: { (action: UIAlertAction!) in print("Cancel!") }) ac.addAction(aDef) ac.addAction(aDes) ac.addAction(aCan) self.present(ac, animated: true, completion:nil) }
できました。
popoverで表示してみます。
UIAlertControllerStyle を actionSheet に変更すると popoverPresentationController の設定を使用できます。
iPhoneだと動作を確認できないので、iPadで実行します。
@IBAction func btnClick(_ sender: UIButton) { let ac = UIAlertController(title:"Title", message: "Message", preferredStyle: UIAlertControllerStyle.actionSheet) let aDef = UIAlertAction(title: "default", style: UIAlertActionStyle.default, handler: { (action: UIAlertAction!) in print("Default!") }) let aDes = UIAlertAction(title: "destructive", style: UIAlertActionStyle.destructive, handler: { (action: UIAlertAction!) in print("Default!") }) let aCan = UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel, handler: { (action: UIAlertAction!) in print("Cancel!") }) ac.addAction(aDef) ac.addAction(aDes) ac.addAction(aCan) ac.popoverPresentationController?.sourceView = self.view ac.popoverPresentationController?.sourceRect = btn.frame self.present(ac, animated: true, completion:nil) }
sourceRect に吹き出しを指したい位置を指定します。