iOS/UIKit

Swift)여러번 호출되는 Alert 경고창 활용

skyiOS 2023. 8. 27. 19:31
반응형
반응형
여러 곳에서 alert를 호출하다 보면 같은 코드가 반복된다.
간단하게 줄여보자.


함수 선언 

UIViewController에서 호출 하기 위해 확장을 통해 함수를 선언 해줍니다.
addButtonText 를 넣어주지 않으면 취소 버튼만 있는 경고창을 띄웁니다.
extension UIViewController{
    func showAlert(text: String, addButtonText: String? = nil, Action: (() -> Void)? = nil) {
        let alert = UIAlertController(title: "경고!", message: text, preferredStyle: .alert)
        
        let cancel = UIAlertAction(title: "취소", style: .destructive)
        alert.addAction(cancel)
        
        if let buttonText = addButtonText {
            let customAction = UIAlertAction(title: buttonText, style: .default) { _ in
                Action?()
            }
            alert.addAction(customAction)
        }
        
        present(alert, animated: true)
    }
}

호출 

기본 경고창을 사용할 부분에서 경고 메세지와 함께 호출해서 사용합니다.
showAlert(text: "ㅠㅠ 제 밥 뺏어가지마세요. 0이상 입력해주세요.")
showAlert(text: "이미키우고있는 다마고치입니다.")
showAlert(text: "준비중입니다.")
addButtonText를 입력 후 클로저에서 실행 할 코드를 적어 사용합니다.
초기화 버튼을 누르면 UserDefaults를 초기화 하고 화면을 바꾸어 줍니다.
showAlert(text: "정말로 초기화 하시겠습니까?", addButtonText: "초기화") {
            if let bundleID = Bundle.main.bundleIdentifier {
                UserDefaults.standard.removePersistentDomain(forName: bundleID)
            }
            self.changeRootView()
        }

 

반응형