简体   繁体   中英

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

Here i'm working with Slider. We can change Slider's accentColor like this,

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

在此处输入图像描述

But how to apply Gradient to an accentColor ?

I tried to apply gradient by masking slider, but then i'm not able to slide it anymore.

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

So is there any indirect way to do it?

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 solution extracted as a standalone view

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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM