SwiftUI中的Slider更改时如何触发函数?

时间:2019-10-16 01:10:10

标签: function slider swiftui

我试图在滑块值更改时触发sliderchanged()函数,我可能缺少一些非常基本的内容,但是发现的所有类似内容均无法正常工作。像Slider的“动作”或旧的“ ValueChanged”动作一样吗?

这是我的代码:

struct CustomSlider1: View {

    @State var progress: Float = 0.5
    var body: some View {

       VStack{
        Slider(value: $progress)
            .padding(.all)
            Text(String(progress))          
        }        
    }

    func sliderchanged() {
        //do things 
    }
}

谢谢!

3 个答案:

答案 0 :(得分:8)

Swift 5,iOS 13

另一种选择,简单地使用State变量和闭包。

@State var alpha = 65
@State var alphaToShow = ""

Slider(value: $alpha, in: 65...90,step: 1,onEditingChanged: { data in
  self.alphaToShow = String(Character(UnicodeScalar(Int(self.alpha))!))
  // execute more code here
}
}).padding()
Text(alphaToShow)

答案 1 :(得分:3)

您可以创建一个自定义Binding,以调用Binding的设置器中的函数:

@State var progress: Float = 0.5
var body: some View {

   VStack{
       Slider(value: Binding(get: {
           self.progress
       }, set: { (newVal) in
           self.progress = newVal
           self.sliderchanged()
       }))
       .padding(.all)
       Text(String(progress))
    }
}

func sliderchanged() {
    print("Slider value changed to \(progress)")
}

答案 2 :(得分:1)

另一种使用 onChange 修饰符获得持续更新的方法。

import SwiftUI

struct SliderOnChange: View {
    @State var progress: Float = 0.5

    var body: some View {
        VStack{
            Slider(value: self.$progress)
                .onChange(of: self.progress) { newProgress in
                    self.sliderChanged(to: newProgress)
                }
            Text(String(self.progress))
        }
    }

    func sliderChanged(to progress: Float) {
        print("Slider value changed to \(progress)")
    }
}