Xcode 应用从另一个 class 访问我的 ViewController 中的元素时出现问题?

Xcode app issues accessing elements in my ViewController from another class?

在我的应用程序中,SubscriptionVC 中有一个按钮,当按下该按钮时,将从 IAPService class 调用 'purchase' 函数。但在函数完成后,我希望使用 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({ [=13=].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)
        }
       
    }
}

}

这是“委托模式”的案例

  1. 创建协议
protocol IAPServiceDelegate {
  func transactionFinished()
}
  1. 在您的 IAPService
  2. 中创建一个 属性 类型的 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 的中间体 class,因此您可能必须使用那个 class 来实现委托或重构您的代码)