我正在传递 @State
使用 @Binding
更改几个 View 在 subview 上,当我最终将变量设置回 false 时,有时我的 View 不会被忽略。
看来我可以运行 articleDisplayed.toggle()
但是如果我在上面或下面运行一个附加功能,它就不起作用了。
知道这里发生了什么吗?
这是我的代码:
struct HomeView: View {
@EnvironmentObject var state: AppState
@State var articleDisplayed = false
// MARK: - Body
var body: some View {
NavigationView {
ZStack {
List {
ForEach(state.cards, id: \.id) { card in
Button(action: {
self.articleDisplayed = true // I set it to true here
self.state.activeCard = card
}) {
HomeCell(
card: card,
publicationColor: self.state.publication.brandColor
)
}.sheet(isPresented: self.$articleDisplayed) {
SafariQuickTopicView(articleDisplayed: self.$articleDisplayed)
.environmentObject(self.state)
.environment(\.colorScheme, .light)
}
}
}
}
}
}
}
然后在我的
SafariQuickTopicView
:struct SafariQuickTopicView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@EnvironmentObject var state: AppState
@Binding var articleDisplayed: Bool
var body: some View {
NavigationView {
ZStack(alignment: .bottom) {
// doesn't matter what's in here
}
.navigationBarItems(trailing: passButton)
}
}
private var passButton: some View {
Button(action: self.state.pass {
DispatchQueue.main.async {
// self.state.removeActiveCardFromState()
self.articleDisplayed.toggle() // this will work but adding a second function in here prevents it from working, above or below the toggle.
}
}
}) {
Text("Pass")
}
}
最后,在我的
AppState
:func pass(completion: () -> Void) { // need completion?
guard let activeCard = activeCard else { return }
if let index = cards.firstIndex(where: { $0.id == activeCard.id }) {
activeCard.add(comment: "pass")
rejectCurrentCard() // Does an async operation with an external API but we don't care about the result
addRemovedActiveCardToUserDefaults()
completion()
}
}
最佳答案
移动.sheet
在列表之外,它必须是每个 View 层次结构一个,所以像
List {
ForEach(state.cards, id: \.id) { card in
Button(action: {
self.articleDisplayed = true // I set it to true here
self.state.activeCard = card
}) {
HomeCell(
card: card,
publicationColor: self.state.publication.brandColor
)
}
}
}
.sheet(isPresented: self.$articleDisplayed) {
SafariQuickTopicView(articleDisplayed: self.$articleDisplayed)
.environmentObject(self.state)
.environment(\.colorScheme, .light)
}
关于ios - SwiftUI:使用@Binding 关闭模态视图不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61580299/