我习惯了 Interface Builder 和布局约束,但现在我想将我的应用程序转换为 Swift UI。我现在想做的是将标有 1 的 View 的顶部边缘对齐到安全区域底部边缘(标有 2)的一定距离内,以便现在位于 1 的顶部边缘将位于位置 3。我尝试使用垫片,但在 iPhone 8 等较小的设备上它看起来会有所不同。在 IB 中,我可以使用简单的布局约束。这在 Swift UI 中是如何工作的?我已附上相关代码和图像。感谢您的帮助。
struct ContentView: View {
init() {
UINavigationBar.appearance().backgroundColor = .orange
}
var body: some View {
NavigationView {
VStack{
Spacer()
ZStack{
Rectangle()
.fill(Color(hue: 0, saturation: 0, brightness: 0, opacity: 0.1))
Image("")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 100, height: 150)
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 4))
.shadow(radius: 10)
}.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width, alignment: .center)
Spacer(minLength: 100)
ZStack(alignment: .bottom){
ExtractedView()
.edgesIgnoringSafeArea(.bottom)
}
}
.navigationBarTitle(Text("You See"))
.navigationBarHidden(false)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewDevice("iPhone")
}
}
struct ExtractedView: View {
@State private var name: String = ""
var body: some View {
VStack{
ZStack(alignment: .top){
VStack{
RoundedRectangle(cornerRadius: 50)
.frame(width: 60, height: 7)
.padding(.top)
Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {
Text("Start advertising")
.font(.headline)
.foregroundColor(Color.black)
}.padding(.top)
TextField("Test", text: $name)
.padding(.all)
.background(Color.white.cornerRadius(20))
.padding()
}
RoundedRectangle(cornerRadius: 30)
.fill(Color(hue: 0, saturation: 0, brightness: 0, opacity: 0.1))
.zIndex(-5)
}
}
}
}
最佳答案
好的,所以我能够解决我的问题。诀窍是创建两个具有不同帧对齐的 VStack。外部VStack采用顶部对齐方式,以便发现 View 可以位于顶部。内部 VStack 具有底部对齐方式,以便可以从底部向上拉动纸张。在这种情况下,空间将从下向上填充。
VStack{
Discover()
.padding(.top, 60.0)
VStack{
Text("Recent Messages:")
.font(.headline)
DetailSheet()
.offset(x: 0, y: 0)
}.frame(width: g.size.width, height: (g.size.height - g.size.width - 80 + 200), alignment: .bottom)
}
.frame(width: g.size.width, height: g.size.height, alignment: .top)
关于swift - 将矩形对齐到安全区域底部边缘一定距离内 SWIFTUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59965665/