iTranslated by AI
How to Make a SwiftUI Button Tappable Even When Disabled
This is a quick tip that came to mind. It was interesting to see it actually work during testing, so I'm making it into an article.
Environment
- iOS 16
- Xcode 14.1
Button.disabled(true)
SwiftUI views provide a disabled(_:) method, which can also be used with Button. Applying it to a Button ensures that it doesn't accept user actions and automatically gives it an appropriate disabled appearance. However, I encountered a situation where I wanted the button to look disabled but still trigger a modal when tapped. While the standard way to achieve this might be to prepare a separate button with a disabled look depending on the state, that felt a bit tedious. In this article, I'll take a different approach to implement this behavior.
Button.disabled: https://developer.apple.com/documentation/swiftui/button/disabled(_:)#
Conclusion
Button {
// Main process
} label: {
Label()
}
.disabled(disabled)
.onTapGesture {
// Logic for the disabled state
}
Adding onTapGesture after Button.disabled works. I interpret this as being possible because applying onTapGesture results in a different View. Note that this won't apply to parts where SwiftUI currently doesn't allow modifications, such as when a Button is placed inside a Menu.
The code example shows a minimal configuration. It works as intended even without adding control logic like if disabled inside onTapGesture, but I think it's fine to include it if you feel it makes the code easier to understand.
Summary
I tried using this for the flow to a paid plan in an app I'm developing personally. It might be interesting to include things like little hidden features.
That's all \(^o^)/
Discussion