Ios 使用setNeedsDisplay成功进行应用内购买后,如何更改按钮图像?

Ios 使用setNeedsDisplay成功进行应用内购买后,如何更改按钮图像?,ios,iphone,swift,swift2,Ios,Iphone,Swift,Swift2,我正在尝试学习如何在iOS上使用应用内购买,我正在练习制作一个简单(对我来说并不简单)的应用 我想做的是,按下一个有背景图像的按钮后,我希望应用程序内的购买流程完成,并且在成功购买时,我希望同一按钮上的背景图像更改为不同的图像 我就是这样尝试的: import UIKit import StoreKit public var currentProductID: String! = "" public var collectionIndex: String = "" class Purchas

我正在尝试学习如何在iOS上使用应用内购买,我正在练习制作一个简单(对我来说并不简单)的应用

我想做的是,按下一个有背景图像的按钮后,我希望应用程序内的购买流程完成,并且在成功购买时,我希望同一按钮上的背景图像更改为不同的图像

我就是这样尝试的:

import UIKit
import StoreKit

public var currentProductID: String! = ""
public var collectionIndex: String = ""

class PurchaseViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {

    @IBOutlet weak var movementsPurchaseButton: UIButton!

    @IBAction func purchaseMovements(sender: UIButton) {
        for product in productArray {
            if product.productIdentifier == "something" {
                currentProductID = product.productIdentifier
                beginTransaction(SKPayment(product: product))
            }
        }
    }

    func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction: SKPaymentTransaction in transactions {
            switch transaction.transactionState {
            case .Purchased:
                SKPaymentQueue.defaultQueue().finishTransaction(transaction)
                didBuyCategory(currentProductID)
                break
            case .Failed:
                ...
            case .Restored:
                ...
            default:
                ...
            }
        }
    }

    func didBuyCategory(collectionIndex: String) {
        defaults.setBool(true , forKey: collectionIndex)
        if (collectionIndex == "something") {
            movementsPurchaseButton.setBackgroundImage(UIImage(named: "Checkbox-528.png"), forState: UIControlState.Normal)
            movementsPurchaseButton.setNeedsDisplay()
        }
        else if ...
        .
        .
    }

}
应用内购买工作正常(我在这里省略了一些功能以作简要说明)。当代码到达这一行时会出现问题:
movementspruchasebutton.setBackgroundImage(UIImage(名为:“Checkbox-528.png”),用于状态:UIControlState.Normal)

错误为
致命错误:在展开可选值时意外发现nil

我可以看到应用程序试图更改其图像的UIView实例全部为零

UIKit.UIViewController  UIViewController    
movementsImageView  UIView! nil None
movementsPurchaseButton UIButton!   nil None

我不明白为什么它是nil,为什么它是按钮的新实例而不是原始按钮,以及我需要做什么才能访问原始按钮。我只想在成功时更改背景图像,为什么这么难?

首先:
didbuycography()
应该在完成事务之前调用。第二:检查图像本身是否正在加载“Checkbox-528.png”第三:您首先是如何设置旧的背景图像的?Ok@Jad我切换了
didBuyCategory()
的顺序。finishTransaction(transaction)
。我用属性检查器在storgyboard UI中添加的原始图像。图像本身也是通过编程加载的,例如,如果我在
viewdiload()
中加载它,它就可以了。“我在storgyboard UI中添加的原始图像”您使用了图像还是背景图像?请尝试使用
DispatchQueue.main.async{//Your setImage或setbackgroundImage}包装setImage或setbackgroundImage
@Jad我在脚本编辑器和代码中都设置了背景图像。我要试一试。