首页 > 解决方案 > 如何将内容视图缩放到多个屏幕尺寸?SwiftUI

问题描述

新手来了!我正在使用 Swiftui 构建一个测验应用程序,我通过在 iPhone 11 模拟器中预览它来构建视图控制器。

而且我认为 controlview 会适合其他 iPhone 尺寸,比如 iPhone 8。因为 Swiftui 具有内置的自动布局。

但是当我运行 iPhone 8 模拟器时,控制视图中的一些内容是不可见的,因为它们位于屏幕下方。

有没有办法解决它?

我尝试使用多个 Spacer() 和不同的填充,但我似乎无法让它同时在两个屏幕上看起来都很好。

这是我的代码:

import SwiftUI

struct questionOne: View {


    @State var totalClicked: Int = 0
    @State var showDetails = false
    @State var isSelected = false

    var body: some View {
        VStack {

            TRpic().frame(width: 350.0, height: 233.0).cornerRadius(10).padding(.top, 80)

            Spacer()

            Text(verbatim: "What's the capital of Turkey?")
                .font(.title)
                .padding(.bottom, 60)
                .frame(height: 100.0)




            Button(action: {}) {

                Text("Istanbul")
            }.buttonStyle(MyButtonStyle())


            Spacer()

            Button(action: {self.isSelected.toggle()}) {
                Text("Ankara")
            }.buttonStyle(SelectedButtonStyle(isSelected: $isSelected))


            Spacer()

            Button(action: {}) {
                Text("Athens")

            } .buttonStyle(MyButtonStyle())

            Spacer()



            NavigationLink(destination: questionTwo()) {
        VStack {
                Text("Next Question")

               Adview().frame(width: 150, height: 60)
                }

               }

            }.edgesIgnoringSafeArea(.top)
        }
    }

struct MyButtonStyle: ButtonStyle {

  func makeBody(configuration:

    Self.Configuration) -> some View {
    configuration.label
      .padding(20)
      .foregroundColor(.white)
      .background(configuration.isPressed ? Color.red : Color.gray)
      .cornerRadius(10.0)
  }
}

struct SelectedButtonStyle: ButtonStyle {

    @Binding var isSelected: Bool

    public func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding(20)
            .foregroundColor(.white)
            .background(isSelected ? Color.green : Color.gray)
            .cornerRadius(10.0)
    }
}

在此处输入图像描述

截屏

标签: swiftui

解决方案


在给定的上下文中,我猜您不想要滚动视图,因此关于间距,我建议使用VStack带间距参数VStack(alignment: .center, spacing: n){ ... }并删除 Spacers,如果在 2 个视图之间您需要比 n 更多的距离,只需使用padding添加一些额外的空间。这应该调整所有内容以适应任何屏幕的高度,包括图像,因此不需要固定框架。

但是,您可能有一个非常宽的图像,可能超出安全区域,因此,您可以将图像的最大宽度设置为屏幕宽度

struct questionOne: View {

   var body: some View {
        GeometryReader { geometryProxy in
            VStack(alignment: .center, spacing: 20) {

                TRpic().frame(maxWidth: geometryProxy.size.width, alignment: .center)
                       .padding([.leading, .trailing], 10)
                  .......               
            }  
        }
   }

推荐阅读