์๋ ํ์ธ์! ์์ดํฐ์ ์ฌ์ฉํ๋ค๋ณด๋ฉด ์๋์ ๊ฐ์ ํ์ ์ฐฝ ๋ง์ด ๋ณด์คํ ๋ฐ์!
์ค๋์ iOS UIAlertController๋ฅผ ์ฌ์ฉํด์ AlertView๋ฅผ ๋์ฐ๋ ๋ฐฉ๋ฒ์ ์์๋ณด๊ฒ ์ต๋๋ค.
๊ตฌ์ฑ์์๋ฅผ ์์๋ดค์ผ๋ Xcode ํ๋ก์ ํธ๋ฅผ ์์ฑํ๊ณ ์ง์ Alert View๋ฅผ ๋์๋ด ์๋ค!
์ฐ์ ๊ฐ๋จํ๊ฒ ์คํ ๋ฆฌ๋ณด๋์ ๋ฒํผ์ ๋๋ฅด๋ฉด Alert View๋ฅผ ๋์ธ ์ ์๋๋ก ๋ฒํผ์ IBAction ์์ ์ฝ๋๋ฅผ ์ง๋ณด๋๋ก ํ๊ฒ ์ต๋๋ค.
โ AlertController
AlertController์์ ์ง์ ํ ๋ถ๋ถ์ ์ฌ๊ธฐ์ ๋๋ค
Alert์ ๊ตฌ์ฑ์์๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค
Title: alert์ ์ ๋ชฉ
Message: alert์ ๋ํ ์์ธํ ๋ด์ฉ์ ์ ๊ณตํ๋ ์ค๋ช ํ ์คํธ
preferredStyle: alert ์ปจํธ๋กค๋ฌ์ ์คํ์ผ - alert, action sheet ๋ ์ข ๋ฃ๊ฐ ์๋๋ฐ ์ค๋ ์ฌ์ฉํ ์คํ์ผ์ alert์ ๋๋ค
๊ฐ ๊ตฌ์ฑ์์์ ๋ง๋ ๊ฐ์ ์ฐจ๋ก๋ก ๋ฃ์ด์ฃผ๋ฉด ๋ฉ๋๋ค. ์ฐธ๊ณ ๋ก title์ ๋ณผ๋, message๋ ๊ธฐ๋ณธ ์์ฒด๊ฐ ๋ค์ด๊ฐ๋๋ค
let alert = UIAlertController(title: "ํ์ดํ์
๋๋ค", message: "๋ฉ์ธ์ง์
๋๋ค", preferredStyle: .alert)
ํน์ title์ด๋ message ๋ ์ค ํ๋๋ง ์ด์ฉํ๊ณ ์ถ๋ค๋ฉด, ์ฐ์ง ์์ ๊ตฌ์ฑ์์์ ๊ฐ์ ""์ผ๋ก ๋ฃ์ด์ฃผ๋ฉด ๋๊ฒ ์ฃ ?
// title๋ง ์ฐ๊ณ ์ถ์ ๋
let alert = UIAlertController(title: "ํ์ดํ์
๋๋ค", message: "", preferredStyle: .alert)
// message๋ง ์ฐ๊ณ ์ถ์ ๋
let alert = UIAlertController(title: "", message: "๋ฉ์ธ์ง์
๋๋ค", preferredStyle: .alert)
โก Alert Action
Alert Action์์ ์ง์ ํ ๋ถ๋ถ์ ์ฌ๊ธฐ์ ๋๋ค!
let action = UIAlertAction(title: "action", style: .default, handler: nil)
UIAlertAction์ ์คํ์ผ์๋ default, cancel, destructive 3๊ฐ์ง๊ฐ ์๋๋ฐ์! ํ๋์ฉ ๋น๊ตํด๋ณผ๊ฒ์
default์ ๋นํด cancel์ ๋ณผ๋ ์คํ์ผ๋ก, destructive๋ ๋นจ๊ฐ์์ผ๋ก ๋ฐ๋ ๊ฒ์ ํ์ธํ ์ ์์ต๋๋ค. ๋ชฉ์ ์ ๋ง๊ฒ ์ฌ์ฉํ์๋ฉด ๋ฉ๋๋ค
โข add Action
์ด์ ์ ๋ง๋ action์ alert์ ๋ถ์ฌ์ค์ผ๊ฒ ์ฃ ? addAction() ํจ์๋ฅผ ์ด์ฉํ๋ฉด ๊ฐ๋จํ๊ฒ ๋ถ์ผ ์ ์์ต๋๋ค!
/* ์ฐธ๊ณ ์ฉ */
// addAction Declaration
func addAction(_ action: UIAlertAction)
alert.addAction(action)
โฃ present
์ด์ action์ด ๋ถ์ alert view๊ฐ ์์ฑ๋์ผ๋๊น presentํด์ฃผ๋ฉด ๋ฉ๋๋ค!
present(alert, animated: true, completion: nil)
๋ค์ ํฌ์คํ ์์๋ ์ด์ด์ UIAlertAction์ handler์ present์ completion์ ์ฌ์ฉํด๋ณด๊ฒ ์ต๋๋ค!
์ ์ฒด์ฝ๋์ ๋๋ค :)
//
// ViewController.swift
// AlertView
//
// Created by ์ฅ์ํ on 2021/02/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func showAlertView(_ sender: Any) {
// 1. alert view ๋ง๋ค๊ธฐ
let alert = UIAlertController(title: "ํ์ดํ์
๋๋ค", message: "๋ฉ์ธ์ง์
๋๋ค", preferredStyle: .alert)
// 2. alert action ๋ง๋ค๊ธฐ
let action = UIAlertAction(title: "ํ์ธ", style: .default, handler: nil)
// 3. alert์ action ๋ถ์ด๊ธฐ
alert.addAction(action)
// 4. alert presentํ๊ธฐ
present(alert, animated: true, completion: nil)
}
}
๋๊ธ ์์ญ