Представление ведет себя иначе в родительском представлении чем в предварительном просмотре - PullRequest
1 голос
/ 08 марта 2020

Я сделал представление в SwiftUI, которое оборачивается внутри кнопки в другом представлении.

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)
                })
            }
        }
    }

enter image description here

Но при реализации в моем приложении они не совпадают размер больше

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)
            }
        }
    }

И это выглядит так:

enter image description here

Почему он так себя ведет? Что я сделал не так?

1 Ответ

1 голос
/ 08 марта 2020

Это эффект сжатия контента - ваша метка "Ежегодно ..." короче, поэтому результирующий вид меньше. Ниже приведена небольшая коррекция вида этикетки.

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()                                     // << here!
                    .foregroundColor(Color(.systemBackground))
            }.padding(.vertical)
            Spacer()                                             // << here!
            VStack(alignment:.trailing) {
                Text("Subscribe")
                    .foregroundColor(Color.green)
                    .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.green)
        .cornerRadius(5)
        .padding(1)
        .cornerRadius(5)
    }
}

Результат: (с замененными пользовательскими цветами)

demo

Протестировано и работает с Xcode 11.2 / iOS 13,2

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...