[iOS] UIAlertController를 이용해 알림창 띄우기

고재경·2020년 12월 15일

UIAlertController는 사용자에게 알림창을 보여주는 기능을 제공해주는 클래스입니다.

1. UIAlertController 인스턴스 만들기
2. UIAlertAction을 통해 항목 만들기
3. 화면에 띄워주기

위의 세가지 단계를 통해 iOS에서 알림창을 사용자에게 보여줄 수 있습니다.

1.UIAlertController 인스턴스 만들기

@IBAction func showAlert(_ sender: Any) {
        let alert = UIAlertController(title: "알림", message: "알림창입니다.", preferredStyle: .alert)
}

위와 같이 버튼을 ViewController와 연결한 후 alert라는 UIAlertController의 인스턴스를 생성을 해줍니다. preferredStyle값을 .actionSheet으로 변경하여 다른 스타일의 알림창을 생성할 수도 있습니다.

2. UIAlertAction을 통해 항목 만들기

@IBAction func showAlert(_ sender: Any) {
        let alert = UIAlertController(title: "알림", message: "알림창입니다", preferredStyle: .actionSheet)
        let confirm = UIAlertAction(title: "확인", style: .default, handler: nil)
        let close = UIAlertAction(title: "닫기", style: .destructive, handler: nil)
}

UIAlertAction을 통해 알림창에서 선택할 수 있는 버튼을 만듭니다. 아래의 결과 화면에서 style 속성에 따라 다른 UI를 확인할 수 있습니다.

3. 화면에 띄워주기

@IBAction func showAlert(_ sender: Any) {
        let alert = UIAlertController(title: "알림", message: "알림창입니다", preferredStyle: .actionSheet)
        let confirm = UIAlertAction(title: "확인", style: .default, handler: nil)
        let close = UIAlertAction(title: "닫기", style: .destructive, handler: nil)
        
        alert.addAction(confirm)
        alert.addAction(close)
        present(alert, animated: true, completion: nil)
    }

UIAlertController의 인스턴스인 alert에 addAction()을 이용해 알림창에 선택지를 추가해줍니다. 그 후, present를 이용하여 사용자의 화면에 알림창을 띄워줍니다.

실행화면


preferredStyle 속성을 actionSheet으로 변경했을때의 결과화면


References

https://junghun0.github.io/2019/05/20/ios-alert/
https://developer.apple.com/documentation/uikit/uialertcontroller

0개의 댓글