我正在嘗試創建 2 個大小相同的按鈕,但大小由按鈕內的文本決定。兩個按鈕分別是“登錄”和“創建賬號”,所以“創建賬號”按鈕比較大。我嘗試使用 .frame() 來調整大小,但這只是讓它周圍有額外的填充。
這是我的代碼:
HStack {
Button(action: {
print("Login button pressed")
}) {
Text("Login")
.padding()
.foregroundColor(Color.white)
.background(Color(UIColor.buttonColor))
.cornerRadius(15)
}
Button(action: {
print("Create Account button pressed")
}) {
Text("Create Account")
.padding()
.foregroundColor(Color.white)
.background(Color(UIColor.buttonColor))
.cornerRadius(15)
}
}
這就是顯示的內容

uj5u.com熱心網友回復:
最好制作一個可以在整個應用程式中使用的按鈕樣式,這也將確保任何未來的堆疊都按比例填充。否則你會發現你的 UI 會變得很亂,用這樣的 Text()s 制作按鈕。
在 HStack 中使用自定義樣式布置按鈕:
HStack(spacing: 20) {
Button("Login", action: { print("login")})
.buttonStyle(PrimaryButtonStyle())
Button("Create Account", action: { print("create account")})
.buttonStyle(PrimaryButtonStyle())
}.padding([.leading, .trailing], 10)
主要按鈕樣式:
struct PrimaryButtonStyle: ButtonStyle {
var backgroundColor: Color = .black
var textColor: Color = Color.white
var height: CGFloat = 46
var cornerRadius: CGFloat = 15
var fontSize: CGFloat = 15
var disabled: Bool = false
var textSidePadding: CGFloat = 30
var weight: Font.Weight = .semibold
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding([.leading, .trailing], textSidePadding)
.frame(maxWidth: .infinity, maxHeight: height)
.background(disabled ? .gray : backgroundColor)
.foregroundColor(textColor)
.cornerRadius(cornerRadius)
.font(.system(size: fontSize, weight: weight, design: .default))
.scaleEffect(configuration.isPressed ? 1.2 : 1)
.animation(.easeOut(duration: 0.2), value: configuration.isPressed)
}
}
結果:
:
uj5u.com熱心網友回復:
.frame 并將寬度設定為 UI 螢屏 - 空白應該可以作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410734.html
標籤:
下一篇:為Tableview解碼一組問題
