Right now, I am in the process of converting from UIKit to SwiftUI. In UIKit, there is a native Close, X-Styled Button – UIButton.ButtonType.close,
like shown below:
I wanted to find the equivalent of this in SwiftUI, if built in to SwiftUI already. It is understandable if Apple hasn’t gotten around to building/converting this yet. I see this also in the Apple Maps App, which I believe is built in SwiftUI, like shown below (on the bottom right corner of the panel):
If there isn’t a built in button styling, how would one go about creating a View for this close button, which would adapt to light and dark mode? Thank you so much!
Edit: In UIKIt’s Storyboard Editor, here is what I am looking for:
4
Answers
SwiftUI does not use concept of "button type", instead you can construct it by yourself, like
*with any other modifiers as you wish
Xcode 13.4 / iOS 15.5
You can use the
xmark.circle.fill
symbol as the system image:⚠️ Note: there is a difference between
xmark.circle.fill
andx.circle.fill
You can embed a UIKit
UIButton
withUIViewRepresentable
.and then
Example:
It is not currently possible to use system button types in SwiftUI including the close button. I’ve submitted FB10380135 to request this addition.
In the meantime, you could make a Button look like the system close button. Mike Stern, an Apple Design Evangelist, noted in an Ask Apple Q&A:
Also note the close button doesn’t change size as the dynamic type size increases/decreases. Do be sure to make its accessibility label “close” and add support for the large content viewer so people using accessibility text sizes can tap and hold the button to reveal a large xmark symbol with the word Close underneath.
I personally would recommend utilizing
UIViewRepresentable
to add a real closeUIButton
button though as opposed to trying to replicate it exactly – see the answer provided by MMP0.