如何将渐变应用于任何视图的 accentColor - SwiftUI

How to apply gradient to an accentColor of any View - SwiftUI

我正在使用 Slider。我们可以这样改变Slider的accentColor

Slider(value: $tip, in: 0...50, step: 1)
     .accentColor(.red) 

但是如何将 Gradient 应用于 accentColor

我尝试通过遮罩滑块应用渐变,但后来我无法再滑动它了。

LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .top, endPoint: .bottom)
     .mask(Slider(value: $tip, in: 0...50, step: 1))

那么有什么间接的方法可以做到吗?

ZStack {
      LinearGradient(
          gradient: Gradient(colors: [.red, .blue]), 
          startPoint: .leading, 
          endPoint: .trailing
      )
      .mask(Slider(value: $val, in: 0...50, step: 1))

      // Dummy replicated slider, to allow sliding
      Slider(value: $val, in: 0...50, step: 1)
          .opacity(0.05) // Opacity is the trick here.
         // .accentColor(.clear) 
         // instead setting opacity, 
         // setting clear color is another alternative
         // slider's circle remains white in this case
}

@Enes Karaosman 解决方案提取为独立视图

import SwiftUI

struct LinearGradientSlider: View {
    @Binding var value: Double
    var colors: [Color] = [.green, .red]
    var range: ClosedRange<Double>
    var step: Double
    var label: String
    
    var body: some View {
        ZStack {
            LinearGradient(
                gradient: Gradient(colors: colors),
                startPoint: .leading,
                endPoint: .trailing
            )
            .mask(Slider(value: $value, in: range, step: step))
            
            // Dummy replicated slider, to allow sliding
            Slider(value: $value, in: range, step: step, label: { Text(label).font(Font.body.lowercaseSmallCaps()) })
                //            .opacity(0.05) // Opacity is the trick here.
                .accentColor(.clear)
            // instead setting opacity,
            // setting clear color is another alternative
            // slider's circle remains white in this case
        }
    }
}