I would like to have different buttons depending on the type of subscription (monthly, yearly) to be able to customize them individually. For the moment my setup works with a For Each (as below) and therefore does not allow me to distinguish between the different products by varying the design of the buttons.
ForEach (currentOffering!.availablePackages) { pkg in
Button {
// BUY
Purchases .shared.purchase(package: pkg) { (transaction, customerInfo, error, userCancelled) in
if customerInfo?.entitlements.all["pro" ]?.isActive == true {
// Unlock that great "pro" content
userViewModel.isSubscriptionActive = true
}
}
} label: {
Text ("\(pkg.storeProduct.subscriptionPeriod!.periodTitle) \(pkg.storeProduct.localizedPriceString)" )
}
.buttonStyle(GenerateButtonStyle2 ())
}
Best answer by joshdholtz
Hey, @Louis-Auguste 👋
This is a great question! I’ve attached some sample code below that shows how to do this.
Looks for the `package.storeProduct.subsciptionPeriod?.unit` This possible values here are `day`, `week`, `month`, and `year` The below example only looks for month and year as you mentioned in your original question Switches button styles (or any view content) based on that var body : some View {
VStack(spacing : 10 ) {
Text("With RevenueCat" )
.padding()
if let offering = self.offering {
ForEach(offering.availablePackages) { package in
Button {
Task {
try await Purchases.shared.purchase(package : package)
}
} label : {
Text(package.storeProduct.localizedTitle)
}.buttonStyle(self.packageButtonStyle(package))
}
}
}
.padding()
}
func packageButtonStyle(_ package: Package) -> PackageButtonStyle {
switch package.storeProduct.subscriptionPeriod?.unit {
case .month?:
return PackageButtonStyle(bgColor : .red)
case .year?:
return PackageButtonStyle(bgColor : .green)
default :
return PackageButtonStyle(bgColor : .gray)
}
}
struct PackageButtonStyle : ButtonStyle {
let bgColor : Color
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding()
.background(self.bgColor)
.foregroundColor(.yellow)
.clipShape(Capsule())
}
}
Hopefully that helps! Let me know if you have any questions on my sample or any further questions and I’ll be happy to help 😊
Thanks!
View original