簡體   English   中英

如何使布局適合屏幕尺寸

[英]How to Fit the layout to the screen size

在此處輸入圖像描述

我剛剛開始學習 Swift。

上圖是我使用 VStack 和 HStack 制作的畫面。

但我想將按鈕或文本放在任何我想要的地方。

在此處輸入圖像描述

這張照片是我通過使用框架調整大小來安排的。

但是,當分辨率改變時,會出現按鈕或文本超出屏幕的問題。

我想保持這種安排並自動適用於各種 iPhone 分辨率。

VStack {
        HStack {
            Text("Hello")
                .font(.largeTitle)
                .fontWeight(.black)
                .foregroundColor(Color.black)
                .multilineTextAlignment(.center)
        }
        VStack {
            HStack {
                VStack {
                    Text("ID")
                        .padding()
                    Text("PW")
                        .padding()
                }
                
                VStack {
                    TextField("ID", text: $ID)
                        .padding()
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    SecureField("password", text: $password)
                        .padding()
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                }
            }
            
        }
        VStack {
            Button(action: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Action@*/{}/*@END_MENU_TOKEN@*/) {
                Text("Login")
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundColor(Color.white)
        
            }
            .padding()
            .background(Color.green.cornerRadius(18))
            Button(action: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Action@*/{}/*@END_MENU_TOKEN@*/) {
                Text("Sign up")
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundColor(Color.white)
            }
            .padding()
            .background(Color.red.cornerRadius(18))
        }
    }

源代碼非常缺乏經驗。

如果您能告訴我這是否是編寫布局的正確方法,我將不勝感激。

使用.frame(maxWidth: .infinity) 這使得View的大小最大化到他們的容器。

另外,在Text而不是Button上使用.background()修飾符。

如果您像代碼一樣在Button上使用.background() ,則Button僅適用於文本區域。

VStack {
    Button(action: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Action@*/{}/*@END_MENU_TOKEN@*/) {
        Text("Login")
            .font(.title)
            .fontWeight(.bold)
            .frame(maxWidth: .infinity, alignment: .center)
            .foregroundColor(Color.white)
            .background(Color.green.cornerRadius(18)) 
    }
    .padding()

    Button(action: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Action@*/{}/*@END_MENU_TOKEN@*/) {
        Text("Sign up")
            .font(.title)
            .fontWeight(.bold)
            .frame(maxWidth: .infinity, alignment: .center)
            .foregroundColor(Color.white)
            .background(Color.red.cornerRadius(18))
    }
    .padding()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM