スクリーンサイズいっぱいのUIViewに半透明の背景色を設定するだけです。
Swift
1private var bgView: UIView!
2
3override func viewDidLoad() {
4 super.viewDidLoad()
5
6 // スクリーン
7 let bounds = UIScreen.main.bounds
8
9 // 半透明背景
10 bgView = UIView(frame: bounds)
11 bgView.backgroundColor = UIColor("#000000", alpha: 0.5)
12 self.view.addSubview(bgView)
13
14 // ボタン
15 let bgButton = UIButton(frame: bounds)
16 bgButton.addTarget(self, action: #selector(closeAlertView), for: .touchUpInside)
17 bgView.addSubview(bgButton)
18
19 // アラート背景
20 let alertView = UIView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: bounds.width * 0.75, height: bounds.height * 0.5)))
21 alertView.center = bgView.center
22 alertView.backgroundColor = .white
23 bgView.addSubview(alertView)
24
25 // 閉じるボタン
26 let button = UIButton(frame: CGRect(x: 32, y: 32, width: 64, height: 32))
27 button.setTitle("閉じる", for: .normal)
28 button.setTitleColor(.black, for: .normal)
29 button.backgroundColor = .green
30 button.addTarget(self, action: #selector(closeAlertView), for: .touchUpInside)
31 alertView.addSubview(button)
32
33}
34
35@objc func closeAlertView(_ sender: UIButton) {
36 bgView.isHidden = true
37}