본문 바로가기
iOS Swift/Study

[Swift] 책 검색 App (9) 책 담을시 얼럿창 띄우기

by 야고이 2024. 5. 9.
728x90

https://i-go-ya.tistory.com/71

 

Swift Delegate 패턴 예제로 알아보기

240430Delegate 패턴은 객체 간의 통신과 이벤트 처리를 위한 디자인 패턴 중 하나입니다. 주로 객체 간의 느슨한 결합(Loose coupling)을 유지하면서 하나의 객체가 다른 객체의 동작을 대신 처리할 수

i-go-ya.tistory.com

 

제가 작성해 놓은 글이랑 아주 똑같은 상황이라 그대로 적용 했습니다

 

프로토콜 생성

protocol DetailViewDelegate {
    func addBookalert(message: String)
}

파라미터에 담은 책 이름을 받을거예요

 

담기 버튼 누를시 델리게이트 사용하여 메서드 호출

delegate?.addBookalert(message: addBook.title ?? "")

담기 버튼을 누를 때 실행 되는 메서드에 위 코드를 추가해 줬어요

@objc func saveAddBook() {
    print("coreData 저장")
    guard let context = self.persistentContainer?.viewContext else { return }
    guard let selectBook = self.selectBook else { return }
    let addBook = Book(context: context)
    addBook.title = selectBook.title
    addBook.salePrice = Int32(selectBook.salePrice)
    addBook.thumbnail = selectBook.thumbnail
    try? context.save()
    self.dismiss(animated: true, completion: nil) // 이전 화면으로 이동
    delegate?.addBookalert(message: addBook.title ?? "")
}

 

 

얼럿 메서드 구현

func addBookalert(message: String) {
    let alertVC = UIAlertController(title: "책 담기 완료!", message: " \(message)이(가) 라이브러리에 담겼습니다.", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "확인", style: .default, handler: nil)
    alertVC.addAction(okAction)
    present(alertVC, animated: true, completion: nil)
}

창이 닫히면서 검색페이지에서 얼럿이 띄워집니다

검색뷰컨트롤러에 프로토콜을 채택하고 메서드를 구현해줍니다

 

728x90

댓글