gpt4 book ai didi

ios - SwiftUI:使用@Binding 关闭模态视图不起作用

转载 作者:行者123 更新时间:2023-12-01 19:32:37 25 4
gpt4 key购买 nike

我正在传递 @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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com