카테고리 없음

[Swift - UIKit] alert 알림창 띄우기

분홍이귀여워 2024. 11. 8. 17:32
반응형

1. Alert 객체 생성

let alert = UIAlertController(title: "전체삭제", message: "해당 날짜의 할 일을 모두 삭제하겠습니까? (개별 삭제는 왼쪽으로 밀어 삭제하세요)", preferredStyle: .alert)

title과 message 를 이용해 얼럿 내용을 작성한다.
preferredStyle 는 화면에 표시되는 스타일로 두가지 옵션이 있다.

.alert - 기본적인 팝업 형식의 얼럿창으로 화면 중앙에 나온다.
.actionSheet - 화면 하단에서 슬라이드 업 방식으로 나온다.

 

2. 버튼 액션 추가

UIAlertAction.Style 에는 3개의 옵션이 있다.
.default - 확인 또는 저장
.destructive - 주로 삭제나 초기화
.cancel - 취소
옵션을 선택해주고 그 뒤에 실행할 코드를 쓰면 된다.

//삭제버튼
let removeButton = UIAlertAction(title: "확인", style: .destructive) { action in
    let todoDatas = todoManager.getParticularTodoData(date: date)
    for data in todoDatas {
    	todoManager.deleteToDo(data: data)
    }
                
    if let addVc = vc as? AddTodoViewController {
    	addVc.setupData(date: date)
    } else if let allVc = vc as? AllTodoListViewController {
        allVc.setupData()
    }
                
    // 데이터 삭제 후 테이블뷰 리로드
    for subView in uiView.subviews {
    	if let tableView = subView as? UITableView {
        	tableView.reloadData()
    	}
    }
}
    
//취소버튼
let cancelButton = UIAlertAction(title: "취소", style: .cancel)

//액션등록
alert.addAction(removeButton)
alert.addAction(cancelButton)

 

3. alert 표시

present 메서드를 통해 화면에 alert 알림창 표시

vc.present(alert, animated: true, completion: nil)

 

 

전체코드

import UIKit

final class AlerHelper {
    
    static func showAlertController(date: Date, vc: UIViewController, todoManager: CoreDataManager, uiView: UIView) {
        
        let alert = UIAlertController(title: "전체삭제", message: "해당 날짜의 할 일을 모두 삭제하겠습니까? (개별 삭제는 왼쪽으로 밀어 삭제하세요)", preferredStyle: .alert)
        
        let removeButton = UIAlertAction(title: "삭제", style: .destructive) { action in
                let todoDatas = todoManager.getParticularTodoData(date: date)
                for data in todoDatas {
                    todoManager.deleteToDo(data: data)
                }
                
                if let addVc = vc as? AddTodoViewController {
                    addVc.setupData(date: date)
                } else if let allVc = vc as? AllTodoListViewController {
                    allVc.setupData()
                }
                
                // 데이터 삭제 후 테이블뷰 리로드
                for subView in uiView.subviews {
                    if let tableView = subView as? UITableView {
                        tableView.reloadData()
                    }
                }
            }
            
        let cancelButton = UIAlertAction(title: "취소", style: .cancel)
            
        alert.addAction(removeButton)
        alert.addAction(cancelButton)
        
        vc.present(alert, animated: true, completion: nil)
    }
}

 

반응형