如何使用SwiftUI创建自定义滑块? [英] How to create custom slider by using SwiftUI?

查看:462
本文介绍了如何使用SwiftUI创建自定义滑块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用SwiftUI创建一个Slider,但不能更改该滑块的样式,如下图所示.

I am able to create a Slider by using SwiftUI but I am not able to change the style of the slider as shown in the image(below).

问题:我无法在SwiftUI中找到任何选项来更改滑块样式.

Problem: I am not able to find any option in SwiftUI to change the slider style.

注意:我只想使用SwiftUI来创建它.我已经使用" https://github.com/daprice/iOS-在Swift中创建了此滑块触觉滑块"

Note: I want to create this by using SwiftUI only. I already created this slider in Swift by using "https://github.com/daprice/iOS-Tactile-Slider"

我尝试了以下方法,但这不是解决方案:

I have tried following but it's not the solution :

1. Slider(value: .constant(0.3)).accentColor(Color.white)

2. Slider(value: $age, in: 18...20, step: 1, minimumValueLabel: Text("18"), maximumValueLabel: Text("20")) { Text("") }

3. Slider(value: $age, in: 18...20, step: 1, minimumValueLabel: Image(systemName: "18.circle"), maximumValueLabel: Image(systemName: "20.circle")) { Text("") }

如何仅使用SwiftUI创建具有图像所示样式的滑块?

How can I create a slider with the style as shown in the image using SwiftUI only?

推荐答案

对我来说,强调色取决于上下文和框架,因此我们不需要处理.

As it turned out for me accent color is depending on the context, as well as the frame, so we don't need to handle that.

就控件而言,我做了一个非常虚拟且简单的示例.请不要将其视为解决方案,而是入门.

As far as the control goes I made a really dummy and simple example. Please do not consider this as a solution, rather a starter.

struct CustomView: View {

    @Binding var percentage: Float // or some value binded

    var body: some View {
        GeometryReader { geometry in
            // TODO: - there might be a need for horizontal and vertical alignments
            ZStack(alignment: .leading) {
                Rectangle()
                    .foregroundColor(.gray)
                Rectangle()
                    .foregroundColor(.accentColor)
                    .frame(width: geometry.size.width * CGFloat(self.percentage / 100))
            }
            .cornerRadius(12)
            .gesture(DragGesture(minimumDistance: 0)
                .onChanged({ value in
                    // TODO: - maybe use other logic here
                    self.percentage = min(max(0, Float(value.location.x / geometry.size.width * 100)), 100)
                }))
        }
    }
}

您可以像

    @State var percentage: Float = 50

    ...
    var body: some View {
    ...
            CustomView(percentage: $percentage)
                .accentColor(.red)
                .frame(width: 200, height: 44)
    ...

这篇关于如何使用SwiftUI创建自定义滑块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆