🔨

Swift - Alertに画像を追加する方法

2022/05/15に公開

完成イメージ

完成コード

ViewController.swift
import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        let alert = UIAlertController(title: "画像付きアラート", message: "画像付きアラートです。", preferredStyle: .alert)
        let imageView = UIImageView(frame: CGRect(x: 10, y: 70, width: 250, height: 250))
        let height = NSLayoutConstraint(item: alert.view!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 380)
        alert.view.addConstraint(height)
        imageView.image = UIImage(named: "CatImage")
        alert.view.addSubview(imageView)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
    
}

ポイント

画像の調整と追加

let imageView = UIImageView(frame: CGRect(x: 10, y: 70, width: 250, height: 250))
imageView.image = UIImage(named: "CatImage")
alert.view.addSubview(imageView)

ここで画像のサイズと座標の指定、画像情報の追加をしています。

画像の挿入スペースの確保

let height = NSLayoutConstraint(item: alert.view!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 380)
alert.view.addConstraint(height)

ここでアラートの高さを指定しています。
これによって画像を挿入する余裕を作っています。

参考記事

https://stackoverflow.com/questions/28340836/add-image-to-alert-view

Discussion