【问题标题】:Xcode app issues accessing elements in my ViewController from another class?Xcode 应用程序问题从另一个类访问我的 ViewController 中的元素?
【发布时间】:2021-01-10 14:55:25
【问题描述】:

在我的应用程序中,SubscriptionVC 中有一个按钮,当按下该按钮时,将调用 IAPService 类中的“购买”函数。但功能完成后,我希望使用 ViewController 的 switchState() 方法更改 ViewController 中的元素。有谁知道该怎么做?

class SubscriptionVC: UIViewController{
@IBOutlet weak var slideBtn: UISegmentedControl!
@IBOutlet weak var testLbl: UILabel!

func switchSubscribeState(){
    testLbl.text = “You have changed this label”
    slideBtn.isHidden=true
}

@IBAction func touchSubscribeBtn(_ sender: Any) {
    TestService.shared.buttonPushed( subsriptionVC:self, product: prod)
}

class IAPService: NSObject {
private override init() {}

static let shared = IAPService()
var currentViewController: SubscriptionVC?

func purchase(subsriptionVC: SubscriptionVC ) {
    currentViewController = subsriptionVC
    guard let productToPurchase = products.filter({ $0.productIdentifier == product.rawValue}).first else {return}
    let payment = SKPayment(product: productToPurchase)
    print("payment",product.rawValue)
    paymentQueue.add(payment)
    
}
}
extension IAPService: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction in transactions {
        switch transaction.transactionState {
        case .failed, .deferred:
            SKPaymentQueue.default().finishTransaction(transaction)
            SKPaymentQueue.default().remove(self)
            break
        case .purchasing:
            break
        case .purchased,.restored:
            //Call switchState() when purchased
            subVC?.switchSubscribeState()
            SKPaymentQueue.default().finishTransaction(transaction)
            
            SKPaymentQueue.default().remove(self)
            break
        default:
            SKPaymentQueue.default().finishTransaction(transaction)
            SKPaymentQueue.default().remove(self)
        }
       
    }
}

}

【问题讨论】:

    标签: ios swift skpaymenttransaction


    【解决方案1】:

    这是“委托模式”的一个案例

    1. 创建协议
    protocol IAPServiceDelegate {
      func transactionFinished()
    }
    
    1. 在您的 IAPService 中创建 IAPServiceDelegate 类型的属性
    var delegate:IAPServiceDelegate?
    
    1. 事务完成时通知委托人。
    case .purchased,.restored:
      SKPaymentQueue.default().finishTransaction(transaction)
      delegate?.transactionFinished()
    
    1. 让您的视图控制器实现该委托
    class SubscriptionVC: UIViewController, IAPServiceDelegate {
    
    1. 将您的视图控制器指定为 IAPService 的委托
    service.delegate = self
    

    (看起来您使用了一个名为 TestService 的中间类,因此您可能必须使用该类来实现委托或重构您的代码)

    【讨论】:

    • 这正是我想要的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2020-03-05
    • 2018-07-13
    相关资源
    最近更新 更多