【问题标题】:Developing a SwiftUI algorithm based on screen size开发基于屏幕大小的 SwiftUI 算法
【发布时间】:2020-06-08 17:02:05
【问题描述】:

所以我有一个滑块,我有一个带有一些文本的小 VStack 框架,当您触摸滑块时我想移动这些文本(我希望 VStack 一直保持在滑块所在位置的正上方)。我不确定是否有更好的方法来做到这一点,所以我尝试通过使其依赖于滑块的值来调整 VStack 的前导填充。这是我的代码:

struct ViewName: View {
    @State private var sliderValue: Double = 0.0
    var body: some View {
        VStack {
        HStack {
            VStack {
                Text("t")
            }.frame(height: 30).background(Color.white)
             .padding(.leading, CGFloat(CGFloat(DayRangeValue) * (UIScreen.main.bounds.width * 0.7)/24) + ((UIScreen.main.bounds.width * 0.15) + 10))
             //The above padding is the algorithm: the addition of (UIScreen.main.bounds.width * 0.15 + 10) essentially works; it tells the VStack the starting position, and works on diff device simulators.
             Spacer()
        }
        Slider(value: $sliderValue, in: 0...23).frame(width: UIScreen.main.bounds.width * 0.7)
        //Note: the 0...23 cannot be changed, and the width of the slider is a percentage of screen size because I figured it can't be some static value, as that would only work on one device
    }
}
}

长话短说,我希望“t”在滑块上方,无论它在哪里;在任何设备上。上述填充算法目前在其中一款 iPad 模拟器上运行良好,但在 iPhone 8 模拟器上无法正常运行(例如)。如果有人可以帮助我找出适用于所有设备的基于屏幕尺寸的填充算法,那就太棒了。

【问题讨论】:

  • 你可以用GeometryReader代替UIScreen.main.bounds
  • @pawello2222 只是做一些快速研究,似乎正确的实现是将 Text("t") 和它在 GeometryReader 中的堆栈放入代码块中紧跟 Slider() 初始化?
  • 我试图运行你的代码,但它不能编译——你的身体只需要返回一个视图——HStackSlider不能同时返回。 DayRangeValue 是什么?
  • @pawello2222 我刚刚更新了它,我把它们都包装在了一个 VStack 中,所以现在它只是一个视图;它应该编译

标签: swift algorithm swiftui padding


【解决方案1】:

如果我正确理解了您的意图,这是可能的解决方案(与几何无关)。使用 Xcode 11.4 / iOS 13.4 测试

let kKnobWidth = CGFloat(24)

struct DemoLabelAboveSlider: View {
    var range: ClosedRange<Double> = 0...23

    @State private var sliderValue: Double = 0.0

    var body: some View {
        VStack(alignment: .leading) {
            Slider(value: self.$sliderValue, in: self.range)
                .padding(.vertical)
                .overlay(GeometryReader { gp in
                    Text("t")
                        .position(x: CGFloat(self.sliderValue) * (gp.size.width - kKnobWidth) / CGFloat(self.range.upperBound) + kKnobWidth / 2, y: 0)
                })
        }
        .padding(.horizontal) // << this one is only for better demo
    }
}

【讨论】:

  • Asperi 你是个 Swift 天才
猜你喜欢
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多