You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:15:36