【发布时间】:2020-03-08 14:51:19
【问题描述】:
我在 SwiftUI 中创建了一个视图,它被包裹在另一个视图中的 Button 中。
struct BuySubscriptionView: View {
var subscriptionText: String = "Monthly Subscription"
var amountText: String = "2.99 € / Month"
var body: some View {
HStack() {
VStack(alignment:.leading) {
Text(subscriptionText)
.bold()
.fixedSize()
.foregroundColor(Color(.systemBackground))
.padding(.bottom, 5)
Text("Access to all exercises")
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(Color(.systemBackground))
}.padding(.vertical)
VStack(alignment:.trailing) {
Text("Subscribe")
.foregroundColor(Color.baseDark)
.padding()
.background(Color.white)
.cornerRadius(5)
.padding(1)
.background(Color.black)
.cornerRadius(5)
Text(amountText).bold()
.foregroundColor(Color(.systemBackground))
.padding(.top)
}.padding(.leading)
}
.padding()
.background(Color.baseDark)
.cornerRadius(5)
.padding(1)
.cornerRadius(5)
}
}
我将它包裹在一个按钮中。当我在 PreviewProvider 中使用它时,一切都会正确生成:
static var previews: some View {
GeometryReader { geometry in
VStack(spacing: 70) {
Spacer()
Button(action: {
}, label: {
BuySubscriptionView(subscriptionText: "Monthly Subscription", amountText: "29.99€/month").frame(width: geometry.size.width * 0.9, height: geometry.size.width * 0.2, alignment: .center)
})
Button(action: {
}, label: {
BuySubscriptionView().frame(width: geometry.size.width * 0.9, height: geometry.size.width * 0.2, alignment: .center)
})
}
}
}
但是在我的应用中实现它时,它们不再具有相同的大小
var body: some View {
GeometryReader { geometry in
VStack {
Text("Hello " + self.userName + "!" ).font(.title)
Spacer().frame(height: geometry.size.height * 0.1)
self.premiumTextView()
.frame(width: geometry.size.width * 0.6)
Spacer().frame(height: geometry.size.height * 0.1)
Group {
if !self.isPremium {
VStack(alignment: .center,spacing: 70) {
Button(action: {
self.buyPremium()
}, label: {
BuySubscriptionView()
.frame(width: geometry.size.width * 0.9, height: geometry.size.width * 0.2, alignment: .center)
})
Button(action: {
self.buyPremium()
}, label: {
BuySubscriptionView(subscriptionText: "Yearly Subscription", amountText: "29.99 € / Year")
.frame(width: geometry.size.width * 0.9, height: geometry.size.width * 0.2, alignment: .center)
})
}
} else {
EmptyView()
}
}
Spacer().frame(height: geometry.size.height * 0.1)
LogInOutButton(action: {
self.logOut()
}, title: "Log out", width: geometry.size.width * 0.7)
}
}
}
看起来像这样:
为什么会这样?我做错了什么?
【问题讨论】: