아미(아름다운미소)

얼럿 사용해 경고 표시하기 (Alert) 본문

랭귀지/SWIFT

얼럿 사용해 경고 표시하기 (Alert)

유키공 2018. 1. 8. 13:00

얼럿 사용해 경고 표시하기(Alert)

얼럿(Alert) 이란


주로 사용자에게 중요한 알림이나 경고 메시지를 나타내야 할 때 사용합니다.

경고메시지를 통해 메시지와 함께 두가지 이상의 선택을 요구할수도 있고 선택에 따라 특정 작업도 수행할 수 있습니다.

전구 켜기, 끄기, 제거 버튼을 만들어 전구를 제어하고 선택에 따라 경고 메시지를 나타내어 그에 따른 작업을 수행하는 앱을 만들어보겠습니다.

import UIKit

class ViewController: UIViewController {
    let imgOn : UIImage = UIImage(named: "lamp-on.png")!
    let imgOff : UIImage = UIImage(named: "lamp-off.png")!
    let imgRemove : UIImage = UIImage(named: "lamp-remove.png")!
    var isLampOn = true
    
    @IBOutlet weak var lampImg: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        //lampImg 객체에 imgOn을 대입합니다.
        lampImg.image = imgOn
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func btnLampOn(_ sender: UIButton) {
        if(isLampOn==true) {
        //전구가 켜져 있을때
        //전구가 켜져 있다고 Alert을 실행함
            //UIAlertController를 생성 합니다.
            let lampOnAlert = UIAlertController(title: "경고", message: "현재 On 상태입니다.", preferredStyle: UIAlertControllerStyle.alert)
            //UIAlertAction을 생성 합니다.(특별한 동작을 하지않을 경우에는 handler를 nil로 합니다.)
            let onAction = UIAlertAction(title: "네,알겠습니다.", style: UIAlertActionStyle.default, handler: nil)
            //생성된 onAction을 얼럿에 추가합니다.
            lampOnAlert.addAction(onAction)
            //presentViewController 메서드를 실행 합니다.
            present(lampOnAlert,animated: true, completion: nil)
        }else{
        //전구가 켜져 있지 않을 때
        //전구를 켬
            lampImg.image = imgOn
            isLampOn=true
        }
    }
    
    @IBAction func btnLampOff(_ sender: UIButton) {
        if isLampOn {
        //전구가 켜져 있을 경우
        //전구를 끌 것인지를 묻는 Alert을 실행
        //if(isLampOn==true)로 작성해도 무방
            //UIAlertController를 생성 합니다.
            let lampOffAlert = UIAlertController(title: "램프끄기", message: "램프를 끄시겠습니까?", preferredStyle: UIAlertControllerStyle.alert)
            //UIAlertAction을 생성 합니다.전등을 꺼야 하므로 핸들러에 중괄호{,}를 넣어 추가적으로 작업을 합니다.
            //반드시 self를 붙여야 에러가 발생하지 않습니다.
            let offAction = UIAlertAction(title: "네", style: UIAlertActionStyle.default, handler: {ACTION in self.lampImg.image = self.imgOff
                self.isLampOn = false
            })
            //UIAlertAction을 추가로 생성 합니다.(특별한 동작을 하지않을 경우에는 handler를 nil로 합니다.)
            let cancelAction = UIAlertAction(title: "아니오", style: UIAlertActionStyle.default, handler: nil)
            //생성된 offAction,cancelAction을 얼럿에 추가 합니다.
            lampOffAlert.addAction(offAction)
            lampOffAlert.addAction(cancelAction)
            //present 메서드를 실행 합니다.
            present(lampOffAlert, animated: true, completion: nil)
        }
    }
    
    @IBAction func btnLampRemove(_ sender: UIButton) {
        //UIAlertController를 생성 합니다.
        let lampRemoveAlert = UIAlertController(title: "램프제거", message: "램프를 제거하시겠습니까?", preferredStyle: UIAlertControllerStyle.alert)
        //UIAlertAction을 생성 합니다.전등을 꺼야 하므로 핸들러에 중괄호{,}를 넣어 추가적으로 작업을 합니다.
        let offAction = UIAlertAction(title: "아니오, 끕니다(off).", style: UIAlertActionStyle.default, handler: {ACTION in self.lampImg.image = self.imgOff
            self.isLampOn = false
        })
        //UIAlertAction을 생성 합니다.전등을 켜는 동작을 추가합니다.핸들러에 중괄호{,}를 넣어 추가적으로 작업을 할수있는데,
        //이번에는 핸들러 매개변수를 삭제하고뒤쪽에{,}를 넣는 방법을 이용합니다.두 가지 방법 모두 에러없이 동작을 구현합니다.
        let onAction = UIAlertAction(title: "아니오, 켭니다(on).", style: UIAlertActionStyle.default) {
            ACTION in self.lampImg.image = self.imgOn
            self.isLampOn=true
        }
        //UIAlertAction을 추가로 생성한 후 전구를 제거하는 동작을 추가 합니다.
        let removeAction = UIAlertAction(title: "네, 제거합니다", style: UIAlertActionStyle.destructive, handler: {
            ACTION in self.lampImg.image = self.imgRemove
            self.isLampOn=false
        })
        //생성된 offAction,onAction,removeAction 을 얼럿에 추가합니다.
        lampRemoveAlert.addAction(offAction)
        lampRemoveAlert.addAction(onAction)
        lampRemoveAlert.addAction(removeAction)
        // present 메서드를 실행합니다.
        present(lampRemoveAlert, animated: true, completion: nil)
    }
}

클로저(Closure) (80~81 라인)

{
            ACTION in self.lampImg.image = self.imgRemove
            self.isLampOn=false
}

를 익명함수, 클로저(Closure)라고 합니다.

클로저란 함수의 축약형으로 이름없는 함수라고도 하며 일반적인 함수의 경우 func 키워드와 함수의 이름을 선언하고 사용하짐나 효율적인 코딩을 위해 함수 이름을 선언하지 않고 바로 함수 몸체만 만들어 사용하는 일회용함수 입니다. 함수를 한번 쓰고 사용하지 않을 때 코딩을 간단히 하고자 사용합니다. 

자세한 내용은 [http://www.todaymart.com/119] 참고 하시구요.


[결과화면]



'랭귀지 > SWIFT' 카테고리의 다른 글

액티비티 인디케이터 구현하기  (0) 2018.01.23
웹 브라우져(Web View)  (0) 2018.01.21
SWIFT 클로저  (0) 2018.01.08
swift 피커 뷰 앱 만들기  (0) 2018.01.07
swift 타이머 사용하여 1초마다 1씩 증가하기  (0) 2018.01.05
Comments