본문 바로가기
개발노트/iOS

[SWIFT] Custom Alert 사용하기

by 전지적진영시점 2023. 2. 19.
반응형

안녕하세요 이번 포스팅에서는

iOS 프로젝트에서 Custom Alert 를 구현하겠습니다

 

준비물 - Xcode, 손가락

 

UIAlertController 클래스를 사용할건데 

iOS dev 문서에는 

 

"이 클래스를 사용하여 표시할 메시지와 선택할 작업으로 경고 및 작업 시트를 구성합니다. 원하는 동작과 스타일로 알림 컨트롤러를 구성한 후 메소드를 사용하여 제시합니다. UIKit은 앱의 콘텐츠 위에 모달 방식으로 경고 및 작업 시트를 표시합니다."

 

라고 정의하네요

 

먼저

UIAlertController 클래스를 사용하기 위해 UIKit를

alert를 띄울 파일 안에 import 해줍니다

 

import UIKit

 

 

아래 코드는 확인 버튼 하나 있는 alert 입니다.

let alertController = UIAlertController(title: "알림", message: "등록되었습니다.", preferredStyle: .alert)
                        
                        let okAction = UIAlertAction(title: "확인", style: .default) { _ in
                            
                        }
                        
                        alertController.addAction(okAction)
                        self.present(alertController, animated: true, completion: nil)

위 코드의 라인을 자세히 봅시다

 

let alertController = UIAlertController(title: "알림", message: "등록되었습니다.", preferredStyle: .alert)

 

먼저 첫번째 줄에 UIAlertCotroller 클래스의 객체를 생성하여 초기화하겠습니다.

변수명은 alertController로 설정했습니도!

 

UiKit의 open class인 UIAlertController의 객체 초기화를 보면

public convenience init(title: String?, message: String?, preferredStyle: UIAlertController.Style)
  • title : 알림 제목이 표시되는 부분, return type은 string
  • message : 알림 내용이 표시되는 부분 , return type은 string
  • preferredStyle : 알림을 표시할 때 스타일

로 간단히 보면 됩니다.

 

let okAction = UIAlertAction(title: "확인", style: .default) { _ in
                            
              }

 

UIAlertAction은 사용자가 알림에서 버튼을 클릭했을 때 발생하는 이벤트입니다.

 

let okAction = UIAlertAction(title: "확인", style: .default) { _ in
               print("Success")             
              }

위 코드처럼 사용자가 확인 버튼을 누를 시 이벤트를 줄 수 있습니다.

 

alertController.addAction(okAction)

 

UIAlertAction 클래스를 사용하여 만든 action을 alertController에 add 해줍시다.

 

self.present(alertController, animated: true, completion: nil)

 

alertController를 실행시켜 줍니다.

 

그렇다면 alert에 버튼을 한개 더 넣어봅시다

 

android처럼 setPositivebutton , setNegativeButton 각각 둘 필요없이

UIAlertAction 클래스를 생성해서 또 만들어주면 됩니다. 물론 객체명까지 동일하면 안되겠지만요!

 

let alertController = UIAlertController(title: "알림", message: "내용내용내용", preferredStyle: .alert)
                
let okAction = UIAlertAction(title: "확인", style: .default) 

let cancelAction = UIAlertAction(title: "취소", style: .default)

alertController.addAction(cancelAction)
alertController.addAction(okAction)


self.present(alertController, animated: true, completion: nil)

 

짠 이상!

 
반응형

댓글