In my data object, I have a dictionary which specifies how many buttons I need to display on the view. I am looping over the dictionary to display the buttons with custom style and when a button is clicked, I intend to display a sheet with content as custom message alert view.
What I am noticing is when I have more than 1 buttons, sheet opens up with custom message alert view only for first button. For other buttons, I do see sheet opening up, but the code in custom view never gets executed.
Code below:
struct CustomActionsView: View {
let dataObject: CustomModel
@State var showingModal: Bool = false
var body: some View {
VStack {
var actionName = ""
// actions is dictionary where key is name that will be displayed on the button and value is name of the image I will be displaying on the button.
ForEach(dataObject.actions.sorted(by: >), id: \.key) { key, value in
let imageName = (key == "Cancel" ? "xmark.circle" : value)
// Button with custom styling.
CapsuleActionButtonWithImage(actionNameText: key, imageName: imageName, action: { self.showingModal.toggle(); actionName = key; NSLog("Clicked action is - \(actionName)") })
.sheet (
isPresented: $showingModal,
content: {
// Only execute the logic for clicked button.
if key == actionName {
// This function always gets called and returns correct data for the button clicked.
let messageViewDetails = Helper.getMessageDetails(dataObject: dataObject, clickedActionName: actionName)
// This gets called only for one button.
GeneralAlertMessageView(imageName: messageViewDetails.messageViewimageName, mainMessageText: messageViewDetails.messageText, messageViewButtonStyle: .okButton, showingModal: $showingModal)
}
}
)
Spacer()
}
}
}
}
Code for GeneralAlertMessageView which should show up whenever any buttons are clicked:
struct GeneralAlertMessageView: View {
var imageName: String?
var mainMessageText: String?
var messageViewButtonStyle: MessageViewButtonStyle = .noButton
@Binding var showingModal:Bool
var body: some View {
VStack {
let _ = NSLog("Within GeneralAlertMessageView")
// Some UI code
}
}
}
Let's say I have 3 key-value pairs within "dataObject.actions" dictionary and hence I will see 3 buttons on the view. When I click on first button, actionName gets set to the name of the button I clicked(within action closure for CapsuleActionButtonWithImage) and getMessageDetails gets executed and "Within GeneralAlertMessageView" gets printed on the console since GeneralAlertMessageView gets displayed on the sheet.
Whenever I click on 2nd and 3rd buttons, actionName gets set to the name of the button I clicked and getMessageDetails does get executed for the button I clicked, but I never see "Within GeneralAlertMessageView" getting printed and all I see is blank sheet. Any breakpoints within GeneralAlertMessageView doesn't hit either.
Am I doing anything wrong? Is there a better way to open sheet for every button click within for loop?
Thanks!