DestructiveButton.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // Copyright © 2022 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import SwiftUI
  17. struct DestructiveButton<Label>: View where Label : View {
  18. private let action: () -> Void
  19. private let label: Label
  20. init(action: @escaping () -> Void, label: () -> Label) {
  21. self.action = action
  22. self.label = label()
  23. }
  24. init(_ titleKey: LocalizedStringKey, action: @escaping () -> Void) where Label == Text {
  25. self.action = action
  26. self.label = Text(titleKey)
  27. }
  28. var body: some View {
  29. if #available(iOS 15, macOS 12, *) {
  30. #if os(iOS) || os(visionOS)
  31. Button(role: .destructive, action: action, label: {
  32. label.foregroundColor(.red)
  33. })
  34. #else
  35. Button(role: .destructive, action: action, label: { label })
  36. #endif
  37. } else {
  38. #if os(iOS) || os(visionOS)
  39. Button(action: action, label: {
  40. label.foregroundColor(.red)
  41. })
  42. #else
  43. Button(action: action, label: { label })
  44. #endif
  45. }
  46. }
  47. }
  48. struct DestructiveButton_Previews: PreviewProvider {
  49. static var previews: some View {
  50. DestructiveButton {
  51. } label: {
  52. Text("Test")
  53. }
  54. }
  55. }