I have a fullscreencover that shows up when I press a button which reads values from another state variable, but when the fullscreencover shows up for the first time, it acts like the variable hasnt changed, and opening after that works perfectly.
Here's some of my code:
@State private var contextMenu = false
@State private var selectedMessage: Message?
List {
ForEach(messages) { message in
Button {
selectedMessage = message
contextMenu = true
} label: {
MessageItem(message: message)
}
.buttonStyle(.plain)
}
}
.fullScreenCover(isPresented: $contextMenu, onDismiss: {selectedMessage = nil}) {
var _ = print(selectedMessage)
if let message = selectedMessage {
VStack {
Text("Select an action.")
Text(message.content)
HStack(alignment: .bottom) {
Button {
} label: {
Image(systemName: "arrowshape.turn.up.left.fill")
}
Button {
} label: {
Image(systemName: "trash.fill")
.foregroundColor(.red)
}
}
}
} else {
Text("No message appears to be selected.")
}
}
The first time the cover opens, it says "No message appears to be selected.", however on subsequent opens it displays the message and message content properly. It might be worth mentioning that I'm running this on watchOS, tested on a simulator and a real device, but I'm still getting the same issue.
In the button, remove the part where you're directly setting the contextMenu boolean.
Button {
selectedMessage = message
} label: {
MessageItem(message: message)
}
.buttonStyle(.plain)
Then, add an onChange trigger in the same rank as your fullScreenCover.
.onChange(of: selectedMessage) { newValue in
contextMenu = newValue != nil
}
That way, it will always trigger after, rather than relying on the lines being synchronous.