Solved

Have Multiple Subscription for each products Buttons with different style in SwiftUI

  • 17 January 2023
  • 2 replies
  • 54 views

Badge

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

 

icon

Best answer by joshdholtz 18 January 2023, 04:25

View original

2 replies

Userlevel 3
Badge +5

Hey, @Louis-Auguste 👋 

This is a great question! I’ve attached some sample code below that shows how to do this.

  1. Looks for the `package.storeProduct.subsciptionPeriod?.unit`
    1. This possible values here are `day`, `week`, `month`, and `year`
    2. The below example only looks for month and year as you mentioned in your original question
  2. 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!

Badge

It works perfectly! Thanks so much :)

Reply