Swift / SwiftUI : how to check if environment /binding var is an empty string (.isEmpty got building error)

1.8k Views Asked by At

I want to have a modal view whenever the avatar is pressed and selected. But when using the binding var, there is no way to know whether it is an empty string..

Codes below:

struct SelectAvatarView: View {
    var role: String
    @State var selectedAvatar: String?
    
    var body: some View {
        NavigationView{
            
            ZStack {
                BackgroundView()

                VStack {
                    TitleTextView(title: "Choose your avatar:")
                    
                    if role == "Parent" {
                        
                        ParentAvatarView(selectedAvatar: $selectedAvatar)
                    }
                    else{
                        ChildAvatarView(selectedAvatar: $selectedAvatar)
                    }
                    Spacer()
                }.padding()
                .sheet(isPresented: !(self.$selectedAvatar.isEmpty) ) { SimpleTestView()}
            }
            
        }
    }
}

Problem is I don't know how to check the binding var $selectedAvatar. no matter what I wrote, errors are:

enter image description here

Cannot convert value of type 'Binding<Bool>' to expected argument type 'Bool'

Help!!! and Thanks!!

2

There are 2 best solutions below

1
On

I don't know how your view architecture.

But here you can fix your compile error by bellow code.

.sheet(isPresented: .constant(!(self.selectedAvatar?.isEmpty ?? false)) ) { SimpleTestView()}
0
On

sorry to all. I was being careless.

But I was hurt by the new "arrogance" of the stackOverflow now. One asks question in Stack as last resort, because last thing he/she wants is to shame himself/herself in front of all the other professional and awesome developers with the stupidity - It ain't fun. But when stuck with project, we had to throw face/dignity outside the window. Only because missing details in the question description, (when it is absolutely irrelevant to the problem), I don't think it deserves a "thumb down", let alone a few.

In the long run, this kind of arrogance will hurt the very purpose of having stackOverflow in the first place.

isPresented only takes Binding<Bool>, that's why, providing a Bool won't work. enter image description here

So I found a workaround by using enter image description here

It is working fine now:

//change avatar to struct Avatar (identifiable) 
@State var selectedAvatar: Avatar?

//change to "item" 
.sheet(item: self.$selectedAvatar ){ avatar in AvatarSummaryView(avatar: avatar)}