【问题标题】:SwiftUI spacer layout issueSwiftUI 间隔布局问题
【发布时间】:2019-11-26 04:24:27
【问题描述】:

我仍在尝试通过创建登录表单来了解 swiftUI。我正在尝试将“forgotPasswordImage”定位在白色圆角矩形的底部,并赋予它相同的宽度(和成比例的高度)。

正如您从屏幕截图中看到的那样,“forgotPassword”图像并没有像我预期的那样位于底部。有趣的是,将以下方法添加到图像中会导致图像向上移动。

Image("forgotPasswordBottom").resizable().relativeWidth(1).scaledToFit()

如何在应用保持正确纵横比的匹配宽度和高度的同时将图像定位在圆角矩形的底部。

谢谢!

import SwiftUI

struct LogIn : View {
    var body: some View {

        ZStack{

            Image("LoginBackground")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .edgesIgnoringSafeArea(.all)

            RoundedRectangle(cornerRadius: 30).foregroundColor(.white).relativeSize(width: 0.8, height: 0.7)

            VStack{
                Spacer()
                Image("forgotPasswordBottom").resizable().relativeWidth(1).scaledToFit()
            }.relativeSize(width: 0.8, height: 0.7)

        }
    }
}

【问题讨论】:

  • 在 macOS Catalina beta 4 发行说明中,他们宣布 SwiftUI 的 relativeWidth、relativeSize 和 relativeHeight 将被弃用。我怀疑他们会为 iOS 保留它们。 Xcode beta 4 尚不可用,但如果没有添加新的修饰符,您的出路可能是使用 GeometryReader:swiftui-lab.com/geometryreader-to-the-rescue 我们可能还需要几个小时才能找到答案。

标签: xcode swiftui


【解决方案1】:

由于 relativeWidth 已被弃用且不可用,如果您想要一个响应式设计,您可以使用UIScreen.main.bounds.width,将此值分配给一个变量,您可以在代码中使用它来获得与屏幕成比例的正确大小的登录框架:

var loginViewWidth = UIScreen.main.bounds.width / 1.3 

我会将登录视图嵌套在单独的第二个 ZStack 中。 另外我会使用这个 ZStack 的 (alignment: .bottom) 修饰符将“forgotPasswordBottom”按钮自动定位到视图的底部,并将修饰符“frame”添加到整个 ZStack,如下所示:

import SwiftUI

struct ContentView: View {

var loginViewWidth = UIScreen.main.bounds.width / 1.3

    var body: some View {
        ZStack{
            Image("LoginBackground")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .edgesIgnoringSafeArea(.all)

            ZStack(alignment: .bottom) {

                RoundedRectangle(cornerRadius: 30).foregroundColor(.white)

                Image("forgotPasswordBottom")
                    .resizable()
                    .aspectRatio(contentMode: .fit)

            }.frame(width: loginViewWidth, height: loginViewWidth * 1.7)
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    相关资源
    最近更新 更多