InListButtonStyle.swift 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // Copyright © 2021 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 InListButtonStyle: ButtonStyle {
  18. fileprivate struct InListButtonView: View {
  19. let configuration: InListButtonStyle.Configuration
  20. @Environment(\.isEnabled) private var isEnabled: Bool
  21. #if os(macOS)
  22. let defaultColor = Color(NSColor.controlColor)
  23. let pressedColor = Color(NSColor.controlAccentColor)
  24. let foregroundColor = Color(NSColor.controlTextColor)
  25. let foregroundDisabledColor = Color(NSColor.disabledControlTextColor)
  26. let foregroundPressedColor = Color(NSColor.selectedControlTextColor)
  27. #else
  28. let defaultColor = Color(UIColor.systemBackground)
  29. let pressedColor = Color(UIColor.systemFill)
  30. let foregroundColor = Color(UIColor.label)
  31. let foregroundDisabledColor = Color(UIColor.systemGray)
  32. let foregroundPressedColor = Color(UIColor.secondaryLabel)
  33. #endif
  34. var body: some View {
  35. #if os(macOS)
  36. ZStack {
  37. RoundedRectangle(cornerRadius: 10.0)
  38. .fill(configuration.isPressed ? pressedColor : defaultColor)
  39. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  40. .shadow(color: .gray, radius: 1, x: 0, y: 0)
  41. .padding(5)
  42. configuration.label
  43. .foregroundColor(isEnabled ? (configuration.isPressed ? foregroundPressedColor : foregroundColor) : foregroundDisabledColor)
  44. }
  45. #else
  46. HStack {
  47. configuration.label
  48. Spacer()
  49. }
  50. .foregroundColor(isEnabled ? (configuration.isPressed ? foregroundPressedColor : foregroundColor) : foregroundDisabledColor)
  51. .contentShape(RoundedRectangle(cornerRadius: 10.0))
  52. .listRowBackground(configuration.isPressed ? pressedColor : defaultColor)
  53. .hoverEffect()
  54. .scaleEffect(configuration.isPressed ? 0.95 : 1)
  55. #endif
  56. }
  57. }
  58. func makeBody(configuration: Configuration) -> some View {
  59. InListButtonView(configuration: configuration)
  60. }
  61. }
  62. extension ButtonStyle where Self == InListButtonStyle {
  63. static var inList: InListButtonStyle {
  64. InListButtonStyle()
  65. }
  66. }