본문 바로가기

Ios

Ios - 간단히 알아보는 UIAlert

UIAlert는 사용자가 어떤 버튼을 눌렀을 때, 화면에 떡하고 나타나는 팝업 형태의 뷰를 말합니다.

 

간단하게 UIAlert를 만들어 보겠습니다.

 

Title과 Message만 있는 Alert

1. Alert를 띄울 버튼 IBAction을 하나 만들어 줍니다.

 

2. UIAlertController(..) 생성자를 통해서 UIAlertController를 하나 만듭니다. 

title - Alert의 제목, message - Alert의 가운데에 나타낸 문구, preferredStyle - .alert과 .actionSheet 중에서 선택, 여기서는 .alert를 선택하겠습니다.

 

3. 작성한 UIAlert를 present(...)를 통해 화면에 띄웁니다.

@IBAction func buttonPressed(_ sender: UIButton) {
        
   let alert = UIAlertController(title: "제목입니다.", message: "이 부분은 내용입니다.", preferredStyle: .alert)
        
   present(alert, animated: true, completion: nil)
    }
}

 

4. 완성

Action 추가

Alert의 하단에 UIAlertAction이라는 UI를 추가 할 수 있습니다.

1. UIAlertAction을 통해 생성합니다.

 

2. UIAlertController의 addAction 메소드에 인자값으로 생성한 UIAlertAction을 넣어 alert에 추가해줍니다.

@IBAction func buttonPressed(_ sender: UIButton) {
        
        let alert = UIAlertController(title: "제목입니다.", message: "이 부분은 내용입니다.", preferredStyle: .alert)
        
        //추가된 부분
        let action = UIAlertAction(title: "yes", style: .default) { (action) in
            
        }
        
        let action2 = UIAlertAction(title: "no", style: .cancel) { (action2) in
            
        }
        
        alert.addAction(action)
        alert.addAction(action2)
        //여기까지가 추가된 부분임.
        
        present(alert, animated: true, completion: nil)
    }
}

3. 완성

 

 

TextField를 추가하는 예시)

let alert = UIAlertController(title: "Alert", message: "Watch out!", preferredStyle: .alert)
        
let action = UIAlertAction(title: "yes", style: .default) { (action) in

        }
        
alert.addTextField { (alertTextField) in
            
            alertTextField.placeholder = "say I am okay"
            textField = alertTextField
        }
        
alert.addAction(action)
        
present(alert, animated: true, completion: nil)

 

'Ios' 카테고리의 다른 글

Ios - Life Cycle과 관련된 메서드들의 실행순서  (0) 2020.04.03
Ios - Custom TableViewCell  (0) 2020.04.03
Ios - UITableView 기본  (0) 2020.02.10
Ios - Firebase의 Authentication 사용하기  (0) 2020.01.29
Ios - CocoaPods  (0) 2020.01.23