围绕 SwiftUI 中的安全区域问题缩放动画

问题描述 投票:0回答:1

我正在尝试调整视图大小,但是当视图(YellowView)放大/缩小到安全区域时,视图中的所有元素都会经历突然的变化(由视图大小的变化引起)。您建议如何解决这个问题以防止突然移动?

import SwiftUI

struct ContentView: View {
    @State private var scale = false
    var body: some View {
        GeometryReader { proxy in
            ZStack {
                YellowView()
                    .ignoresSafeArea()
                    .offset(x: 100)
                    .scaleEffect(scale ? 0.8 : 1)
                                    
                Button {
                    withAnimation(.easeInOut(duration: 3)) {
                        scale.toggle()
                    }
                } label: {
                    Text("Scale")
                }
                .frame(maxWidth: .infinity,alignment: .leading)
                .padding()
            }
        }
        
    }
}

struct YellowView: View {
    var body: some View {
        ZStack {
            HStack {
                Text("TopBar")
                    .frame(maxWidth: .infinity)
                    .background(Color.gray)
            }
            .frame(maxWidth: .infinity,maxHeight: .infinity, alignment: .top)
            
            VStack {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundStyle(.black)
                Text("Hello, world!")
            }
            .padding()
            .background(.cyan)
        }
        .padding()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(.yellow)
    }
    
}

#Preview {
    ContentView()
}

swiftui view scale swiftui-animation xcode15
1个回答
0
投票

首先,应用缩放效果后应应用

.ignoreSafeArea

YellowView()
    .offset(x: 100)
    .scaleEffect(scale ? 0.8 : 1)
    .ignoresSafeArea()

在此之后,您应该看到动画有点平滑,但背景填充仍然从“填充整个安全区域”跳到“不填充任何安全区域”。这是因为

background
默认情况下会尝试填充整个安全区域。

要禁用该功能,请将空集传递给

ignoresSafeAreaEdges
参数。

struct YellowView: View {
    var body: some View {
        ZStack {
            HStack {
                Text("TopBar")
                    .frame(maxWidth: .infinity)
                    .background(Color.gray, ignoresSafeAreaEdges: [])
            }
            .frame(maxWidth: .infinity,maxHeight: .infinity, alignment: .top)
            
            VStack {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundStyle(.black)
                Text("Hello, world!")
            }
            .padding()
            .background(.cyan, ignoresSafeAreaEdges: [])
        }
        .padding()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(.yellow, ignoresSafeAreaEdges: [])
    }
    
}
© www.soinside.com 2019 - 2024. All rights reserved.