美文网首页SwiftUI
SwiftUI 2.0 使用ScrollViewReader

SwiftUI 2.0 使用ScrollViewReader

作者: 刘铁崧 | 来源:发表于2021-02-26 14:33 被阅读0次

可以配合ScrollView 或者ListView使用,控制滚动式图到指定位置
scrollview 使用 scrollviewreader

struct ContentView: View {
    var body: some View {
        ScrollViewReader{
            proxy in
            Button("滚动到指定位置"){
                withAnimation {
                    proxy.scrollTo(50,anchor: .top)//anchor可以设置目标滚动显示到屏幕指定的上中下位置
                }
            }
            ScrollView(.vertical, showsIndicators: false){
                ForEach(1 ... 100,id:\.self){
                    index in
                    Text("第\(index)行")
                        .frame(width: 100, height: 20
                               , alignment: .leading)
                        .id(index)
                }
            }
        }
    }
}

List使用scrollviewreader

  • 注意:如果使用List必须指定id,否则滚动无法生效
struct ContentView: View {
    var body: some View {
        ScrollViewReader{
            proxy in
            
            Button("滚动到指定位置"){
                withAnimation {
                    proxy.scrollTo(30,anchor: .center)//anchor可以设置目标滚动显示到屏幕指定的上中下位置
                }
            }
            List(1 ..< 100,id:\.self){
                index in
                Text("\(index)")
            }
        }
    }
}

相关文章

网友评论

    本文标题:SwiftUI 2.0 使用ScrollViewReader

    本文链接:https://www.haomeiwen.com/subject/fturfltx.html