Language/Swift

[Swift]UIAlertController

jaewpark 2023. 1. 11. 09:34

UIAlertController

경고 메시지를 표시하는 개체

 UIAlertController (
    title: String?,
    message: String?,
    preferredStyle: UIAlertController.Style
)
  • title : 문자열을 사용하여 사람들의 주의를 끌고 경보 이유를 전달
  • message : 경고 이유에 대한 추가 세부 정보를 제공하는 설명 텍스트
  • preferredStyle : 경고 컨트롤러를 표시할 때 사용할 스타일로 이 매개변수를 사용하여 경고 컨트롤러를 작업 시트 또는 모달 경고로 구성

title을 nil로 설정하면, message가 title 같이 굵은 글씨로 표시 title, message를 nil로 설정하면 AlertAction만 표시

UIAlertController.Style

  • case actionSheet : 뷰 컨트롤러가 표시하는 작업 시트
  • case alert : 모달로 표시되는 경고

case actionSheet
case alert

addAction

경고 또는 작업 시트에 작업 개체를 첨부 경고에 여러 작업이 있는 경우 해당 작업을 추가하는 순서에 따라 결과 경고 또는 작업 시트의 순서가 결정

func addAction(_ action: UIAlertAction)
  • action : 경고의 일부로 표시할 작업 개체로 버튼으로 표시

preferredAction

원하는 작업을 지정하면 경고 컨트롤러가 해당 작업의 텍스트를 강조 표시하여 강조

액션 시트에서는 사용 불가

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

addAction보다 늦게 실행된다면 컴파일 과정에서 에러 발생

UIAlertAction

사용자가 알림에서 버튼을 누를 때 취할 수 있는 조치 경고 작업 개체를 만든 후 해당 경고를 사용자에게 표시하기 전에 개체에 추가

UIAlertAction(
    title: String?,
    style: UIAlertAction.Style,
    handler: ((UIAlertAction) -> Void)? = nil
)

UIAlertAction.Style

  • default : 작업 버튼에 기본 스타일을 적용
  • cancel : 작업이 작업을 취소하고 변경되지 않은 상태로 있음을 나타내는 스타일을 적용preferredAction이 포함된 Cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)

  • destructive : 작업이 데이터를 변경하거나 삭제할 수 있음을 나타내는 스타일을 적용
let cancelAction = UIAlertAction(
		title: "Sign out",
		style: .destructive,
		handler: {(_: UIAlertAction!) in
				//Sign out action
    })



참고 : 공식문서, 블로그