[IOS] Alert, ActionSheet

2022. 12. 3. 16:32IOS

Alert & ActionSheet

https://developer.apple.com/documentation/uikit/windows_and_screens/getting_the_user_s_attention_with_alerts_and_action_sheets

 

Apple Developer Documentation

 

developer.apple.com

 

 

 

ios를 사용하다 보면 위의 사진과 같은 화면을 종종 확인할 수 있다. 왼쪽은 alert 오른쪽은 action sheet이라고 불린다. alert과 action sheet은 사용자의 추가정보나 승인이 필요한 경우 사용된다. 하지만 공식문서에서는 이 두 개가 앱의 정상적인 흐름을 중단시키기 때문에 필요한 경우에만 사용되어야 한다고 강조하고 있다.

 

그럼 이제 공식문서에 나온 코드를 살펴보려고 한다. 공식 문서에서는 agreeToTerms라는 함수 안에서 alert 창을 띄웠다. alert창을 띄우기 위해서는 UIAlertController 매서드가 필요하다.

@IBAction func agreeToTerms() {
   // Create and configure the alert controller.     
   let alert = UIAlertController(title: "Terms and Conditions",
         message: "Click Agree to accept the terms and conditions.",
         preferredStyle: .alert)
}

해당 매서드의 파라미터인 preferredStyle에 .alert 혹은 .actionSheet 값을 주어 상황에 따라 알맞은 창을 띄울 수 있다.

 

위의 사진과 같이 OK, Settings와 같은 버튼을 만들어 주고 싶다면, UIAlertAction 매서드와 UIAlertAction을 alert에 넣어주는 addAction 매서드가 필요하다. 만일 추가적인 action을 취하고 싶다면 주석처리된 부분에 필요한 action을 작성해주면 된다.

@IBAction func agreeToTerms() {
   // Create and configure the alert controller.     
   let alert = UIAlertController(title: "Terms and Conditions",
         message: "Click Agree to accept the terms and conditions.",
         preferredStyle: .alert)

   // Create the action buttons for the alert.
   let defaultAction = UIAlertAction(title: "Agree", 
                        style: .default) { (action) in
	// Respond to user selection of the action.
   }
   let cancelAction = UIAlertAction(title: "Disagree", 
                        style: .cancel) { (action) in
	// Respond to user selection of the action.
   }
   
   alert.addAction(defaultAction)
   alert.addAction(cancelAction)
}

 

 

마지막으로 present로 alert을 띄우면 끝이다. 

@IBAction func agreeToTerms() {
   // Create and configure the alert controller.     
   let alert = UIAlertController(title: "Terms and Conditions",
         message: "Click Agree to accept the terms and conditions.",
         preferredStyle: .alert)
         
   // Create the action buttons for the alert.
   let defaultAction = UIAlertAction(title: "Agree", 
                        style: .default) { (action) in
	// Respond to user selection of the action.
   }
   let cancelAction = UIAlertAction(title: "Disagree", 
                        style: .cancel) { (action) in
	// Respond to user selection of the action.
   }
   
   alert.addAction(defaultAction)
   alert.addAction(cancelAction)
        
   self.present(alert, animated: true) {
      // The alert was presented
   }
}

 

 

여기까지가 공식문서 제공하는 Guide line이다. 필자는 이를 이용해 alert에 textfiled를 추가해 text를 받아오고 label에 넣어주도록 코드를 작성해 보았다.

 

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var MainLable: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    var text : String = "(정해진 문구가 없습니다.)" {
        didSet{
            self.MainLable.text = text
        }
    }

    @IBAction func tapAddBtn(_ sender: UIButton) {
        let alert = UIAlertController(title: "문구 등록", message: nil, preferredStyle: .alert)
        
        let RegisterBtn = UIAlertAction(title: "등록", style: .default) { _ in
            guard let text = alert.textFields?[0].text else {return}
            if text != "" {
                self.text = text
            }
        }
        let CancleBtn = UIAlertAction(title: "취소", style: .cancel)
        
        alert.addTextField{textField in
            textField.placeholder = "문구를 적어주세요"
        }
        
        alert.addAction(RegisterBtn)
        alert.addAction(CancleBtn)
        
        self.present(alert, animated: true)
    }
}