首页 > 解决方案 > 我的 if 语句中的 Text() 会改变 if 语句的结果吗?

问题描述

这是我正在使用的代码片段:

struct FindFriendsResultsList: View {
    
    @EnvironmentObject var view_model: CreateEventViewModel
    @State private var followAll: Bool = false
    
    var body: some View {
        VStack {
            Toggle(isOn: $followAll) {
                Text("Follow all friends")
            }
            ScrollView {
                VStack {
                   ForEach(self.view_model.contact_list_decoded["contacts"] ?? [], id: \.self) { user in
                       VStack {
                            if self.followAll == true {
                                UserRow(user: user, action: "Success")
                            }
                            else {
                                UserRow(user: user)
                            }
                        }
                    }
                }
            }
        }  

奇怪的是,除非我包含在条件中,if self.followAll == true否则条件永远不会等于真。Text(String(self.followAll))然后切换按预期工作。这看起来像:

if self.followAll == true {
    Text(String(self.followAll))
    UserRow(user: user, action: "Success")
}
else {
    UserRow(user: user)
}

我只是不想包含Text(String(self.followAll))并且希望这个条件仅与内部的 UserRow 一起使用。

编辑:这里有更多代码。我正在从中剥离任何 UI,并尝试提供尽可能具体的示例。:

struct UserRow: View {
    @State var action: String = "AddFriend"
    
    var body: some View {
        HStack {
            if action == "AddFriend" {
                Image("addfriendicon")
            }
            else if action == "Success" {
                Image("Successicon")
            } 
        }
        
    }
}

标签: swiftswiftuiswift5

解决方案


尝试以下

   ForEach(self.view_model.contact_list_decoded["contacts"] ?? [], id: \.self) { user in
         UserRow(user: user, follow: self.followAll) // << move decision inside
    }

struct UserRow: View {
    let user: YOUR_USER_TYPE
    let follow: Bool           // if more needed, make enum
    
    var body: some View {
        HStack {
            if follow {
                Image("Successicon")
            } else {
                Image("addfriendicon")
            }
        }
    }
}

推荐阅读