iOS - SwiftUI Alert 오류! 이상한 Alert가 뜬다.

2024. 2. 5. 23:58코딩일기/iOS

 

로그아웃과 회원탈퇴 버튼에 Alert 를 띄워서 확인하는 로직을 짜려고 했다.

근데 로그아웃을 눌렀는데 회원탈퇴 Alert 가 뜨기도 하고 

회원탈퇴 버튼을 눌렀는데 로그아웃 Alert 가 뜨기도 했으며

로그아웃만 누르는데 회원탈퇴와 로그아웃 Alert가 번갈아 뜨기도 했다. 

 

다음은 위와 같은 현상일때의 코드다.

    @State private var showing = false
    
    var body: some View {
        HStack {
    		Button(action: {showing = true}) {
            
            }            
            .alert("로그아웃 하기", isPresented: $showing) {
                Button ("아니오", role: .cancel) { }
                Button("네") { profileVM.handleKakaoLogout() }
                
            Button(action: {showing = true}) {
            }
            .alert("회원탈퇴 하기", isPresented: $showing) {
                Button ("아니오", role: .cancel) { }
                Button("네") { profileVM.handleKakaoUnlink() }
            }
        }
    }

 

Alert 를 보이기 위한 상태값 showing 을 중복으로 사용하고 있었기에 빨리 변경되는 것이 랜덤으로 나오고 있겠구나라는 생각이 문득 스쳐 지나갔다.

 

    @State private var showingLogout = false
    @State private var showingUnlink = false
    
        
    var body: some View {
        HStack {
            Button(action: { self.showingLogout.toggle() }) {
                CustomText(title: "로그아웃", textColor: .customGray, textWeight: .semibold, textSize: 16)
            }
            .alert(isPresented: $showingLogout) {
                let firstButton = Alert.Button.cancel(Text("취소")) {

                }
                let secondButton = Alert.Button.default(Text("로그아웃")) {
                    profileVM.handleKakaoLogout()
                    isNextScreenActive = true
                }
                return Alert(title: Text("로그아웃"),
                             message: Text("정말로 로그아웃 하시겠습니까?"),
                             primaryButton: firstButton, secondaryButton: secondButton)
            }
            
            //...
            
            Button(action: { showingUnlink = true }) {
                //...
            }
            .alert(isPresented: $showingUnlink) {
                //...
                return Alert(title: Text("회원탈퇴"),
                             message: Text("정말로 탈퇴 하시겠습니까?"),
                             primaryButton: firstButton, secondaryButton: secondButton)
            }
        }
        .fullScreenCover(isPresented: $isNextScreenActive,
                         content: { LoginView() })
    }

 

Alert 를 띄우기 위한 상태값을 각각 만들어주니 오류가 나지 않았다.

같은 변수를 공유한다는건 서로 의존성을 높이는 코드이기 때문에 안좋은 코드라는걸 깨닫게 되었다...

독립성을 높이는 코드를 짜야겠다.

 

true/false 를 바꿔주는 toggle() 의 사용과 Alert의 사용법을 익히게 되었다. 

반응형