이끼의 생각

iOS 알림창 만들기 (1) 본문

Mobile App/iOS와 Swift

iOS 알림창 만들기 (1)

IKKIson 2019. 4. 16. 16:38

안드로이드의 Alert 메시지 처럼 안드로이드에서도 간단하게 구현할 수 있다.

 

1. 우선 UIAlertController 객체를 생성한다.

 

let alertController = UIAlertController(title: "title string", message: "message contents", preferredStyle: .alert)

 

여기서 preferredStyle은 .alert으로 하면된다.

 

2.  그 다음 원하는 기능 버튼들을 추가하면된다.

alertController.addAction(UIAlertAction(title: "button's title", style:  , handler: )

addAction에서 원하는 액션(알림창 내의 버튼)의 이름과 액션의 종류, 액션 후 작업(handler)를 원하는데로 작성할 수 있다. 

 

- 확인 버튼 만들기

alertController.addAction(UIAlertAction(title: "확인", style: .default, handler: .nil))

or

alertController.addAction(UIAlertAction(title: "확인", style: .default, handler: { code }))

 

 

style은 버튼의 종류라고 생각하면된다. 위 확인버튼의 .default 스타일은 평범한 버튼을 만드는 것이다.

버튼 추가 시 addAction 함수의 handler 파라미터는 클릭 후의 작업을 정할 수 있다.

아무 작업이 일어나지 않고 싶으면 .nil, 이후의 작업을 원하면 소스코드를 작성하면된다.

handler 속성을 정하는 것은 다른 style 속성에서도 원하는데로 작성할 수 있다.

 

- 취소 버튼 만들기

alertController.addAction(UIAlertAction(title: "취소", style: .cancle, handler: nil)

 

취소버튼의 style은 미리 선언된 .cancle을 사용하면 되며 글씨체는 bold체이다.

 

- 경고 버튼 만들기

alertController.addAction(UIAlertAction(title: "경고", style: .destructive, handler: {alertAction in print("경고")}))

 

* 주의 : AlertController에서 경고기능이 있는 것이 아니라 제가 임의로 액션의 이름을 만든 것입니다~~ *

style이 .destructive으로 선언하면 빨간색의 글씨색으로 보여준다. 일반적으로 삭제, 경고 등의 주의가 필요한 버튼들을 선언할때 사용하면 좋다.

 

3. 화면에 보여주기

위의 단계까지 버튼을 만들었으면 이제 원하는 시점에 Alert을 보여줘야된다. 즉 원하는 곳에 다음의 함수를 선언하면 Alert창이 보일 것이다.

present(alertController, animated: true, completion: nil)

 

미리 설정한 alertController객체를 present함수로 넣는다. animated는 애니메이션 효과를 true/false로 정할 수 있다.

마지막으로 present가 완료되어 화면이 보여지면 completion의 코드가 실행된다.

 

ex)

@IBAction func pressBtnAlert() {
	let alertController = UIAlertController(title: "알림창", message: "알림 내용", preferredStyle: .alert)
	alertController.addAction(UIAlertAction(title: "확인", style: .default, handler: {alertAction in print("확인")}))
    alertController.addAction(UIAlertAction(title: "취소", style: .cancle, handler: nil)
	alertController.addAction(UIAlertAction(title: "경고", style: .destructive, handler: {alertAction in print("경고!")}))
	self.present(alertController, animated: true, completion: nil)
}

'Mobile App > iOS와 Swift' 카테고리의 다른 글

iOS Toast 메세지 만들기 (3)  (0) 2019.04.16
iOS Toast 메세지 만들기 (2)  (0) 2019.04.16
iOS Toast 메세지 만들기 (1)  (0) 2019.04.16
Life Cycle - 라이프 사이클  (0) 2019.04.02
CocoaPods  (0) 2018.12.05
Comments