Old_SWIFT(221012)/기본이야기

알림창(UIAlertAction, Alert, ActionSheet, addTextField) 다루기

KataRN 2022. 1. 25. 14:43
반응형

안녕하세요. KataRN입니다.

 

오늘은 알림창에 대해 알아보겠습니다.

알림창의 경우 활용도가 높아 자주쓰는 기능입니다. 

알림창은 UIAlertController로 만들 수 있습니다.

preferredStyle에따라 .alert, .actionSheet로 나눠집니다.

 

아래 애플 공식문서 링크 남기겠습니다.

https://developer.apple.com/documentation/uikit/uialertcontroller

 

Apple Developer Documentation

 

developer.apple.com

 

우선 알림창 코드와 사진을 보여드리겠습니다.

@IBAction func touchUpAlertButton(_ sender: UIButton) {

	let alert = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
        
	let okAction = UIAlertAction(title: "ok", style: .default, handler: nil)
	let removeAction = UIAlertAction(title: "destructive", style: .destructive, handler: nil)
	let cancelAction = UIAlertAction(title: "cancel", style: .cancel, handler: nil)
        
	alert.addAction(okAction)
	alert.addAction(removeAction)
	alert.addAction(cancelAction)
        
	present(alert, animated: true, completion: nil)        
}

보시는 바와 같이 알림창은 가운데에 뜨도록 되어있으며 제목, 메시지내용, 확인버튼, 취소버튼, 강조버튼을 넣을 수 있습니다.

버튼의 개수는 필요한만큼 원하는대로 추가하면됩니다.

 

 

이제 actionSheet의 코드와 사진을 보도록 하겠습니다.

@IBAction func touchUpActionSheetButton(_ sender: UIButton) {
        
	let alert = UIAlertController(title: "title", message: "message", preferredStyle: .actionSheet)
        
	let okAction = UIAlertAction(title: "ok", style: .default, handler: nil)
	let removeAction = UIAlertAction(title: "destructive", style: .destructive, handler: nil)
	let cancelAction = UIAlertAction(title: "cancel", style: .cancel, handler: nil)
    
	alert.addAction(okAction)
	alert.addAction(removeAction)
	alert.addAction(cancelAction)
        
	present(alert, animated: true, completion: nil)
}

 

alert과의 차이는 뜨는 위치와 cancel의 스타일 방식입니다. (actionSheet는 하단에 노출됩니다.)

나머지는 똑같습니다.

위에 보시면 handler에 값을 nil로 넣어뒀습니다. handler에 버튼을 눌렀을때 어떻게 처리할지를 넣어두면 버튼의 기능을 구현 할 수 있습니다.

 

(220206 추가내용)

 

알럿창에 텍스트필드를 추가해보겠습니다.

      alert.addTextField(configurationHandler: { textField in
        textField.placeholder = "이렇게 사용하면됩니다."
      })

 

그럼 데이터값은 어떻게 쓸까요?

ok버튼을 눌렀을때 textField에 있는 내용을 사용한다고 가정해볼게요.

//수정전
let okAction = UIAlertAction(title: "ok", style: .default, handler: nil)

//수정후
let okAction = UIAlertAction(title: "ok", style: .default, handler: { [weak self] _ in
    guard let title = alert.textFields?[0].text else { return }	
    print(title)
})

이렇게 하면 ok눌렀을때 title이 프린트됩니다.

 

앞서 말씀드렸듯이 활용도가 높은 기능이니 한번쯤은 제대로 봐두셔도 좋을 것 같습니다.

 

오늘도 읽어주셔서 감사합니다.

반응형