【问题标题】:How to return values from struct in SwiftUI?如何从 SwiftUI 中的结构返回值?
【发布时间】:2020-05-12 21:31:23
【问题描述】:

我根据以下视频制作了 RangeSlider:https://www.youtube.com/watch?v=5whzc_9eR78。它工作正常,但我想从中获取左右值,我该怎么做?

我的代码:

struct RangeSlider: View {

    @State var width: CGFloat = 0
    @State var width1: CGFloat = 20
    @State var totalWidth: CGFloat = UIScreen.main.bounds.width-60

    let circleSize: CGFloat = 21

    var body: some View {
        VStack{
            ZStack(alignment: .leading){
                Rectangle()
                    .fill(Color.black.opacity(0.2))
                    .frame(width: self.totalWidth+2*self.circleSize, height: self.circleSize/3)

                Rectangle()
                    .fill(Color.black)
                    .frame(width: self.width1-self.width, height: self.circleSize/3)
                    .offset(x: self.width+self.circleSize)

                HStack(spacing: 0){
                    Circle()
                        .fill(Color.white)
                        .frame(width: self.circleSize, height: self.circleSize)
                        .offset(x: self.width)
                        .gesture(
                            DragGesture()
                                .onChanged({ (value) in
                                    if (value.location.x >= 0 && value.location.x <= self.width1){

                                        self.width = value.location.x

                                    }
                                }))

                    Circle()
                        .fill(Color.white)
                        .frame(width: self.circleSize, height: self.circleSize)
                        .offset(x: self.width1)
                        .gesture(
                            DragGesture()
                                .onChanged({ (value) in
                                    if (value.location.x <= self.totalWidth-(2*self.circleSize) && value.location.x >= self.width){

                                        self.width1 = value.location.x

                                    }
                                }))
                }

            }
        }
    }
}

我在我的 ContentView.swift 中的 ZStack 中调用 RangeSlider(),我想返回左拇指值 width/totalWidth 和右拇指值 width1/totalWidth,因为它在 Textfield 中完成(文本:自我.$value) 将文本返回到变量“value”。

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    添加

    @Binding var left: CGFloat
    @Binding var right: CGFloat
    

    然后在width 和width1 改变时设置它们。构建 RangeSlider 时需要传入 Bindings:例如RangeSlider(left: $left, right: $right)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 2014-03-01
      • 1970-01-01
      • 2014-11-19
      • 2020-03-03
      相关资源
      最近更新 更多