UIAlertControllerは拡張高い

UIAlertControllerはサブクラス化が禁止されていますが、内部では色々な事ができるように作られています。setValueを使うと上部にViewControllerを追加できるので画像を表示できるようにカスタマイズしてみました。取りあえずiOS10と11で動きます。

  • 画像表示
  • ダイナミックフォント対応
  • チェックマーク表示
  • 項目が多い時のスクロール対応
  • アラビア語でも大丈夫かも

目次

使ってみる

CustomAlertController

カスタムしたCustomAlertControllerに上部に表示させるVCを追加します。

アクションシート

iPadでのポップオーバー表示もできます。

SubtitleAlertController ActionSheet
@IBAction func actionSheetButtonTouched(_ sender: UIBarButtonItem) {
    let alert = CustomAlertController(title: "Very cute", message: "Animal, Pet, Cat", preferredStyle: .actionSheet)

    let storyboard = UIStoryboard(name: String(describing: CustomAlertSubtitleViewController.self), bundle: nil)
    let vc = storyboard.instantiateInitialViewController() as! CustomAlertSubtitleViewController
    vc.image = UIImage(named: "Cat")
    vc.text = alert.title
    vc.detailText = alert.message

    alert.contentViewController = vc
    alert.checkedIndex = 1

    alert.popoverPresentationController?.barButtonItem = sender

    alert.addAction(UIAlertAction(title: "SNS", style: .default) { (action: UIAlertAction) in
    })
    alert.addAction(UIAlertAction(title: "Mail", style: .default) { (action: UIAlertAction) in
    })
    alert.addAction(UIAlertAction(title: "Download", style: .default) { (action: UIAlertAction) in
    })
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) in
    })
    present(alert, animated: true, completion: nil)
}

アラート

テキストフィールドを複数追加しても崩れません。

SubtitleAlertController Alert
@IBAction func alertButtonTouched(_ sender: UIBarButtonItem) {
    let alert = CustomAlertController(title: "Very cute", message: "Animal, Pet, Cat", preferredStyle: .alert)

    let storyboard = UIStoryboard(name: String(describing: CustomAlertSubtitleViewController.self), bundle: nil)
    let vc = storyboard.instantiateInitialViewController() as! CustomAlertSubtitleViewController
    vc.image = UIImage(named: "Cat")
    vc.text = alert.title
    vc.detailText = alert.message

    alert.contentViewController = vc
    alert.checkedIndex = 1

    alert.addTextField() { (text: UITextField) in
    }
    alert.addAction(UIAlertAction(title: "SNS", style: .default) { (action: UIAlertAction) in
    })
    alert.addAction(UIAlertAction(title: "Mail", style: .default) { (action: UIAlertAction) in
    })
    alert.addAction(UIAlertAction(title: "Download", style: .default) { (action: UIAlertAction) in
    })
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) in
    })
    present(alert, animated: true, completion: nil)
}