swift - SwiftUI ScrollView 滚动到相对位置
问题描述
我有一个不适合屏幕的大水平视图,所以我把它放到了一个水平视图中ScrollView
。如果 0 代表完全向左滚动,而 1 代表完全向右滚动 - 我怎样才能滚动到 0.8 的相对位置?
由于我无法将 id 附加到子元素ScrollViewReader
似乎不起作用。
struct ContentView: View {
var body: some View {
ScrollView(.horizontal) {
Text("Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on.")
}
}
}
解决方案
使用SwiftUI-Introspect,用于“从 SwiftUI 内省底层 UIKit 组件”,我们可以实现这一点。
这是它的完成方式,并附有一个Slider
来证明它的工作原理:
struct ContentView: View {
@State private var relativePosition: CGFloat = 0.5
var body: some View {
VStack {
ScrollView(.horizontal) {
Text("Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on. Example for a long view without individual elements that you could use id on.")
}
.introspectScrollView { scrollView in
let width = scrollView.contentSize.width - scrollView.frame.width
scrollView.contentOffset.x = relativePosition * width
}
let _ = relativePosition // Needed to update view
Slider(value: $relativePosition, in: 0 ... 1)
}
}
}
推荐阅读
- javascript - 我想使用 Jquery 向我的 html 元素添加更多 css 属性,这意味着我不想删除前一个,只是简单地添加更多
- mysql - MySQL:如何对每组中的数据进行排序?
- html - 当我添加浮点数时:对;对于我的代码,我失去了主容器的高度,即
- angular - 在 Ionic Framework 上键入文本时,动态表单字段导致对输入的关注松散
- algorithm - 如果身体可以的话,我该如何解决带有负面物品的背包问题?
- python - COLAB 中的 CAFFE2
- javascript - 使用 google sheet 发送电子邮件
- java - onSuccess/onFailure 可以替换 vert.x 中 CompositeFuture 的 setHandler 吗?
- node.js - 以 HTML 格式显示 MongoDB 集合数据
- ruby-on-rails - 如何使用 ruby 访问 Windows 活动目录中的文件