✅ Solved: Multiple Swift views sharing the same RiveViewModel
Hello!
I’m a tech-artist starting out with Rive and I’m trying to include a shop widget in our ios app.
My problem is that I can’t seem to be able to have multiple instances of my widget while setting individual properties for each one.
To illustrate, this is what it looks right now with all numbers being equal.
While not visible here, the speed of the animation also increases with each new instance added to my scroll view.. 😄
Here’s my code
let starterBundleViewModel = RiveViewModel(fileName: "starter_bundles", fit: .fitWidth, alignment: .topCenter)
struct RiveStarterBundleView: View {
var price : Float
var numChests : Int
var numCoins : Int
var numDiamonds : Int
var inst : RiveDataBindingViewModel.Instance?
// @StateObject var starterBundleViewModel = RiveViewModel(fileName: "starter_bundles", fit: .fitWidth, alignment: .topCenter)
init (price : Float, numChests : Int, numCoins : Int, numDiamonds : Int) {
self.price = price
self.numChests = numChests
self.numCoins = numCoins
self.numDiamonds = numDiamonds
let starterBundleFile = starterBundleViewModel.riveModel!.riveFile
guard let specialOfferCardModel =
starterBundleFile.viewModelNamed("SpecialOfferViewModel") else {
print("Could not find model")
return
}
inst = specialOfferCardModel.createDefaultInstance()
guard let inst = self.inst else {
print("Could not create instance")
return
}
starterBundleViewModel.riveModel!.stateMachine!.bind(viewModelInstance: inst)
setNumberProperty(propertyName: "Price", value: price)
setNumberProperty(propertyName: "Box Amount", value: Float(numChests))
setNumberProperty(propertyName: "Coin Amount", value: Float(numCoins))
setNumberProperty(propertyName: "Gems Amount", value: Float(numDiamonds))
}
func setNumberProperty(propertyName: String, value: Float) {
guard let inst = self.inst else {
return }
if let property = inst.numberProperty(fromPath: propertyName) {
property.value = value
}
else {
print("Could not find prop \(propertyName)")
}
}
var body: some View {
starterBundleViewModel.view()
//.background(Color.red.opacity(0.5))
.frame(height: 180)
}
}
struct RiveStarterBundleViewTest: View {
var body: some View {
ScrollView(.vertical){
VStack{
RiveStarterBundleView(price: 40, numChests: 3, numCoins: 78, numDiamonds: 3)
RiveStarterBundleView(price: 80, numChests: 5, numCoins: 100, numDiamonds: 3)
RiveStarterBundleView(price: 80, numChests: 5, numCoins: 200, numDiamonds: 3)
Spacer()
}.padding(5)
}
.ignoresSafeArea()
}
}
#if DEBUG
#Preview {
ZStack {
BackgroundView()
RiveStarterBundleViewTest()
}
}
#endif
I’d love to get pointers on how to make this work or of examples of this usecase.
Thanks so much!
Seb