使用StoreKit开发iPhone内购:提取HStack后如何获取product对象?
解决方案
你需要把提取出来的HStack封装成一个自定义SwiftUI View,并通过参数传入它需要的SKProduct和StoreManager实例,就能脱离List的循环上下文独立使用。
步骤1:创建自定义Product行View
新建一个SwiftUI文件(比如命名为ProductRow.swift),代码如下:
import SwiftUI import StoreKit struct ProductRow: View { // 传入当前产品和StoreManager实例 let product: SKProduct let storeManager: StoreManager var body: some View { HStack { VStack { Text(product.localizedTitle) Text(product.localizedDescription) } Spacer() if UserDefaults.standard.bool(forKey: product.productIdentifier) { Text("Purchased") } else { Button(action: { storeManager.purchaseProduct(product: product) }, label: { Text("Buy for \(product.price) $") }) } } } }
步骤2:在原List中使用自定义View
修改原来的List代码,用ProductRow替换原来的HStack:
List(storeManager.myProducts, id: \.self) { product in ProductRow(product: product, storeManager: storeManager) }
说明
- 自定义View通过属性接收外部传递的依赖数据,不管你把这个View放在哪里(比如单独页面、弹窗里),只要传入对应的产品和StoreManager实例,就能正常工作。
- UserDefaults判断、购买调用、价格展示的逻辑和原代码完全一致,只是把依赖的
product和storeManager从循环上下文改成了外部传入。
内容的提问来源于stack exchange,提问作者Alexnnd
相关产品推荐
相关产品推荐

