Alert 띄우기
Alert은 alert 과 actionSheet 두 종류가 있다.
alert
@IBAction func alert(_ sender: UIButton) {
//alert 인스턴스 만들기
let alert: UIAlertController = UIAlertController(title: "타이틀 영역", message: "메세지 영역", preferredStyle: .alert)
//alert 액션 정의하기
let alertAction: UIAlertAction = UIAlertAction(title: "기본", style: .default, handler: nil)
let alertAction2: UIAlertAction = UIAlertAction(title: "취소", style: .cancel, handler: nil)
//alert 인스턴스 액션 추가하기
alert.addAction(alertAction)
alert.addAction(alertAction2)
//alert 인스턴스 띄우기
present(alert, animated: true, completion: nil)
}
버튼을 눌렀을 때 알림창이 뜨도록 했다.
위 코드의 경우 alertAction2의 스타일이 .cancel 로 되어 있으며, .cancel의 경우 인스턴스에 한 개 이상이 추가될 경우 오류가 난다.
또한, 액션의 추가 순서와 상관없이 .cancel의 경우 가장 왼쪽에 배치된다.
실행결과는 다음과 같다.

여기서 UIAlertAction의 스타일은 총 3가지인데 .default와 .cancel 외에 .destructive를 추가하면 다음과 같다.
@IBAction func alert(_ sender: UIButton) {
//alert 인스턴스 만들기
let alert: UIAlertController = UIAlertController(title: "타이틀 영역", message: "메세지 영역", preferredStyle: .alert)
//alert 액션 정의하기
let alertAction: UIAlertAction = UIAlertAction(title: "기본", style: .default, handler: nil)
let alertAction2: UIAlertAction = UIAlertAction(title: "취소", style: .cancel, handler: nil)
let alertAction3: UIAlertAction = UIAlertAction(title: "추가한 스타일", style: .destructive, handler: nil)
//alert 인스턴스에 액션 추가하기
alert.addAction(alertAction)
alert.addAction(alertAction2)
alert.addAction(alertAction3)
//alert 인스턴스 띄우기
present(alert, animated: true, completion: nil)
}
경고창의 액션이 3개 이상일 경우 좌, 우 로 배치되는 것이 아닌 목록형으로 배치된다. 새로 추가한 스타일의 경우 중요한 결정을 뜻하기 위해 빨간색으로 강조되어 나타난다. 실행결과는 다음과 같다.

actionSheet
actionSheet는 기본적으로 alert과 달리 확인 혹은 취소등 버튼을 누르지 않고 외부를 터치하는 것 만으로 actionSheet를 없앨 수 있다.
alert과 똑같이 정의해보면 preferredStyle에서 차이점이 있다.
@IBAction func actionSheet(_ sender: UIButton) {
//alert 인스턴스 만들기
let alert: UIAlertController = UIAlertController(title: "타이틀 영역", message: "메세지 영역", preferredStyle: .actionSheet)
//alert 액션 정의하기
let action: UIAlertAction = UIAlertAction(title: "기본", style: .default, handler: nil)
let action2: UIAlertAction = UIAlertAction(title: "취소", style: .cancel, handler: nil)
//alert 인스턴스에 액션 추가하기
alert.addAction(action)
alert.addAction(action2)
//alert 인스턴스 띄우기
present(alert, animated: true, completion: nil)
}
실행결과는 다음과 같다.

마찬가지로 .destructive를 추가한 경우는 다음과 같다.
@IBAction func actionSheet(_ sender: UIButton) {
//alert 인스턴스 만들기
let alert: UIAlertController = UIAlertController(title: "타이틀 영역", message: "메세지 영역", preferredStyle: .actionSheet)
//alert 액션 정의하기
let action: UIAlertAction = UIAlertAction(title: "기본", style: .default, handler: nil)
let action2: UIAlertAction = UIAlertAction(title: "취소", style: .cancel, handler: nil)
let action3: UIAlertAction = UIAlertAction(title: "추가한 스타일", style: .destructive, handler: nil)
//alert 인스턴스에 액션 추가하기
alert.addAction(action)
alert.addAction(action2)
alert.addAction(action3)
//alert 인스턴스 띄우기
present(alert, animated: true, completion: nil)
}
실행결과는 다음과 같다.

이처럼 actionSheet의 경우 버튼의 수와 상관없이 늘 리스트 형식으로 버튼이 배치된다.
또한 취소 버튼의 경우는 가장 하단에 위치한다.