I am using a Form in SwiftUI based on a tutorial from YouTube, and I have placed some components inside it. However, when I tap the button, it doesn't show the tap animation (For example, when I tap a Button in the iOS settings app the button background will change) when I lightly tap it once. Here is my code:
var body: some View {
Form {
Section(header: Text("Input:")) {
TextField("Add Some text here", text: $text)
}
Section(header: Text("Letter: Count")) {
let charCount = text.filter({ $0 != " " }).count
if (charCount > 30) {
Text(String(charCount)).foregroundColor(.red)
} else {
text == "" ? Text("Empty") : Text(String(charCount))
}
}
Section(header: Text("actions")) {
Button("Save Data") {
UserDefaults.standard.set(text, forKey: "TEXT_Key")
}
// When I lightly clicked it, the inner code will be executed, but no visual effect will be shown.
}
}
}
If this question seems silly, please forgive me
My Xcode version: 14.3 (14E222b). Target device: iPhone 14 Pro Simulator and iOS 16.5 for True Device
I have searched Google and found no explanations or solutions regarding this specific issue. I have tried compiling the code using the Release configuration, but the issue still persists.
The expected result is that my button should behave like the buttons in the iOS Settings app, where even a light tap triggers a background color change.
This is a know issue with Forms, Buttons are not working properly and there is no real fix (as far as I know), Section cells will override the Button click with the weird behaviour you are observing. You can try a "clean" workaround like the one I'll post but this may not be what you are seeking for:
Section(header: Text("actions")) {
HStack { // A that superView will handle the button click instead of the Section cell
Button(
action: {
UserDefaults.standard.set(text, forKey: "TEXT_Key")
},
label: {
Text("Save Data")
.frame(maxWidth: .infinity, alignment: .leading) //frame to infinity inside label will apply the button click area to the whole stack
})
}
}.buttonStyle(.borderless) //set a buttonStyle on the Section to display the animation correctly
// Clicking the button lightly will not make the classic section animation (turning to gray) but the text will toggle opacity as classic button do.