SwiftUI ScrollView 内容框架和偏移量 [英] SwiftUI ScrollView content frame and offset

查看:129
本文介绍了SwiftUI ScrollView 内容框架和偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下这个 ScrollView 测试代码的行为——为什么我不能滚动到左​​边缘和上边缘,为什么我可以滚动到右边缘和下边缘之外?以及如何解决这个问题.(请注意,如果我们删除 VStack,行为不会改变.)

Can someone explain the behavior of this ScrollView test code -- why I can't scroll to the left and top edges, and why I can scroll beyond the right and bottom edges? And how to fix this. (Note that if we remove VStack the behavior does not change.)

    var body: some View {

        ScrollView.init([.vertical,.horizontal]) {

            VStack {
                Text("AAA")
                    .padding(8)
                    .frame(width: 1024, height: 1024)
                    .background(Color.orange)
                    .border(Color.red)
            }

        }
        .border(Color.blue)

    }

在这张图片中,我可以滚动到最左边和最上面——它不会滚动到边缘:

In this image is as far to the left and up as I can scroll -- it doesn't scroll to the edges:

但在这里我可以滚动到底部和右侧边缘之外:

But here I can scroll beyond the bottom and right edges:

推荐答案

或者你可以尝试每个方向使用一个ScrollView,试试这个

Or you can try to use one ScrollView for each direction, try this

import SwiftUI

struct ContentView: View {
    var body: some View {

        ScrollView(.horizontal, showsIndicators: true) {
            ScrollView(.vertical, showsIndicators: true) {
                Color.yellow.frame(width: 1024, height: 1024)
                    .overlay(Text("A").font(.largeTitle), alignment: .topLeading)
                    .overlay(Text("B").font(.largeTitle), alignment: .topTrailing)
                    .overlay(Text("C").font(.largeTitle), alignment: .bottomTrailing)
                    .overlay(Text("D").font(.largeTitle), alignment: .bottomLeading)
            }
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

更新

为了能够看到使用 .offset 修饰符会发生什么,请尝试想象此代码段的结果

to be able to see, what happens using .offset modifier, try imagine the result of this snippet

import SwiftUI

struct ContentView: View {
    var body: some View {

        HStack {
            Text("Hello").padding().background(Color.yellow).offset(x: 20, y: 40).border(Color.red)
            Text("World").padding().background(Color.pink).offset(x: -10, y: -10).border(Color.yellow)
            }.padding().border(Color.gray)

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

这篇关于SwiftUI ScrollView 内容框架和偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆