728x90
tableView를 배우면서 여러가지를 부가적으로 배웠는데 그 중 어플에서 가장 많이 사용되는 Alert에 대해 알아보겠습니다!
왼쪽은 Alert, 오른쪽은 ActionSheet로 불립니다!
Alert는 경고, 중요정보, 문제사항을 알릴 때 사용이 됩니다.
ActionSheet는 사용자가 고를 수 있는 액션이 여러 개일 때 사용됩니다.
일단 Alert를 생성하는 법 부터 알아보겠습니다.
//Alert 생성
let alert = UIAlertController(title: "Hello", message: "This is Alert", preferredStyle: .alert)
//AlertAction 정의
let actionDefault = UIAlertAction(title: "default", style: .default, handler: nil)
let actionCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let actionDestructive = UIAlertAction(title: "destructive", style: .destructive, handler: nil)
//AlertAction 추가
alert.addAction(actionDefault)
alert.addAction(actionCancel)
alert.addAction(actionDestructive)
//Alert 표시!
self.present(alert, animated: true, completion: nil)
UIAlertController로 alert의 기본 화면을 생성할 수 있습니다.
파라미터 중 preferredStyle에 .alert 와 .actionSheet 중 사용할 스타일을 정해주면 됩니다.
그 다음 UIAlertAction으로 Alert의 버튼을 만들어 줍니다!
action의 style은 default, cancel, Destructive로 3가지 존재합니다.
파라미터 중 handler는 버튼을 눌렀을 때 동작을 클로저 형식으로 넣어줄 수 있습니다.
마지막으로 present를 사용해 alert를 화면에 띄워주면 끝입니다!
alert.addTextField(configurationHandler: { label in
label.placeholder = "text box"
})
alert에는 텍스트 필드를 기본적으로 넣을 수 있습니다!
actionSheet에는 안됩니다. 코드작성에는 문제가 없지만 실행해보면 오류가 나요.
let v = UIViewController()
v.view.backgroundColor = UIColor.green
alert.setValue(v, forKey: "contentViewController")
alert화면에 ViewController를 넣어서 custom화면을 띄울 수도 있습니다!
alert에 setValue를 사용하여 ViewController를 등록할 수 있습니다.
728x90