티스토리 뷰

Frontend/iOS

UI Alert Controller 에 대한 이해

데니 Denny 2019. 7. 29. 14:38
반응형
SMALL

iOS  개발에 있어서 반드시 사용할 수 밖게 없는 Component가 있습니다. 바로 UI Alert Controller입니다.

Android에서는 Dialog라고 불리는 것인데 iOS에는 UI Alert Controller가 2가지 형태로 제공됩니다.

1. alert
2. actionsheet

iOS Alert(좌)와 Action Sheet(우)

Component의 이름이 생소해서 이게 뭐지? 했을 것이지만, 막상 이미지를 보니 아~ 이런 거구나 하고 생각했을 것입니다.

iOS 에서 Swift를 사용하여 위 2가지 컴포넌트를 간단하게 구현해보도록 합시다.

UI Alert

우선 아래의 코드를 보도록 합시다. uiAlertAction을 정의하기 전에 dialog를 띄워줄 버튼 이벤트를 연결합니다. (IBAction)

@IBAction func onClickButton(_ sender: Any) {
    let alert = UIAlertController(title: "MyTitle",
                                  message: "MyMessage",
                                  preferredStyle: .alert)
        
    let btnCancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        print("Cancel Clicked.")
    }
        
    let btnLogout = UIAlertAction(title: "OK", style: .default) { (action) in
        print("OK Clicked.")
    }
        
    alert.addAction(btnCancel)
    alert.addAction(btnLogout)
    present(alert, animated: false, completion: nil)
}

파헤쳐보기 전에 전체 소스를 살펴보도록 합시다. 우선 alert라는 이름의 객체를 생성해줍니다.

이 객체의 타입은 UIAlertController네요. title과 message를 입력해주시고 preferredStyle에 .alert를 입력해줍니다.

.alert 가 위에서 본 좌측의 형태로 나오는 것을 의미합니다. preferredStyle을 지정해주지 않으면 default로 actionSheet 됩니다. 

우측의 형태를 원한다면 .actionSheet로 하면 됩니다.

 

그 다음 버튼을 정의하고 있습니다. 버튼의 타입은 UIAlertAction이고 .cancel, .default, .destructive 3가지 형태가 있습니다.

.cancel : Bold Style이 적용되며 취소 버튼 생성 시 반드시 이 옵션을 사용할 것.
.default : Default Style
.destructive : 빨간색 Style이 적용되나 Bold는 적용되지 않음.

 

이제 버튼에 대한 Action을 연결해보도록 합시다.

let btnCancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
    print("Cancel Clicked.")
}

마지막에 "{ (action) in " "}" 사이에 원하는 액션을 넣어주시면 됩니다. 만약 여러 줄이 들어가야할 경우에는 별도의 함수를 작성해도 좋고 MVP Pattern이라면 presenter와 연결해 주셔도 좋습니다.

UI Action Sheet

@IBAction func onClickButton(_ sender: Any) {
    let alert = UIAlertController(title: "MyTitle",
                                  message: "MyMessage",
                                  preferredStyle: .actionSheet)
        
    let btnCancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
        print("Cancel Clicked.")
    }
        
    let btnLogout = UIAlertAction(title: "OK", style: .default) { (action) in
        print("OK Clicked.")
    }
        
    alert.addAction(btnCancel)
    alert.addAction(btnLogout)
    present(alert, animated: false, completion: nil)
}

위와 동일한 코드인데 하나 다른 점이 있습니다. 바로 prefferedStyle이 .actionSheet라는 점입니다.

질문) .alert에 버튼은 몇개까지 넣을 수 있나요?

alert에는 버튼을 최대 2개까지 넣을 수 있습니다. 3개 이상의 버튼을 넣고 싶다면 actionSheet를 사용해야 합니다.

 

다시한 번 강조하지만 취소목적을 위한 버튼은 반드시 .cancel로 설정해야 합니다!

반응형
LIST
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함