swift - 我的 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")
}
}
}
}
解决方案
尝试以下
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")
}
}
}
}
推荐阅读
- python - 如何从这个 Pandas 数据系列中只绘制月份和日期(没有年份)?
- flutter - 透明PNG着色的背景颜色
- godot - 如何在场景启动中延迟自定义操作?
- javascript - Bot doesn't go over switch case properly | Discord.js v12
- python - 多个索引的相关性
- r - 在矩阵中查找除 0 以外的唯一元素
- reactjs - MapBox 使用动态数据点
- elasticsearch - Elasticsearch - 所有分片都未分配
- java - Android Studio 上的 ScrollView 按钮消失
- bash - 在 bash 中显示数据网格