首页 > 解决方案 > SKLabelNode 不会从函数更新文本

问题描述

我有这个游戏项目,它有一个硬币系统。我还可以选择让用户观看视频广告,以将 50 个硬币添加到他们的总数中。由于商店页面是 SKScene,我通过视图控制器运行广告,当它完成展示时,视图控制器在场景中运行一个函数,该函数应该更新硬币数量和显示它们的标签。

这是我的视图控制器的代码:

class GameViewController: UIViewController , GADRewardBasedVideoAdDelegate {

var rewardBasedVideo: GADRewardBasedVideoAd!
var rewardvideoisinprogress = false
var interstitial: GADInterstitial!

var adcounter = 0

override func viewDidLoad() {
    super.viewDidLoad()

    adcounter = UserDefaults.standard.integer(forKey: "AdCounter")
    print(adcounter)

    createandloadvideoad()

    interstitial = GADInterstitial(adUnitID: "ca-app-pub-3343126174384559/7308554354")
    let request = GADRequest()
    interstitial.load(request)

    ThemeShop().updatecoins()

    NotificationCenter.default.addObserver(self, selector: #selector(GameViewController.presentvideoad), name: NSNotification.Name("video"), object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(GameViewController.inter), name: NSNotification.Name("inter_"), object: nil)

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "MainMenu") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

        view.ignoresSiblingOrder = true 
    }
}

@objc func inter(){
    adcounter = adcounter + 1
    print(adcounter)
    if adcounter == 2{
        adcounter = 0
        if interstitial.isReady {
            interstitial.present(fromRootViewController: self)
            interstitial = createad()
        } else {
            print("Ad wasn't ready")
        }
    }
    UserDefaults.standard.set(adcounter, forKey: "AdCounter")  
}

func createad() -> GADInterstitial {
    let inter = GADInterstitial(adUnitID: "ca-app-pub-3343126174384559/7308554354`")

    inter.load(GADRequest())

    return inter
}

func createandloadvideoad(){
    rewardBasedVideo = GADRewardBasedVideoAd.sharedInstance()
    rewardBasedVideo?.delegate = self
    if !rewardvideoisinprogress && rewardBasedVideo?.isReady == false{

        //ca-app-pub-3343126174384559/3425197396
        rewardBasedVideo?.load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
        rewardvideoisinprogress = true
    }
}

@objc func presentvideoad(){
    if rewardBasedVideo?.isReady == true{
        rewardBasedVideo?.present(fromRootViewController: self)

    }else{
        print("Was NOt Reardyadjfsjfsalfkj")

    }
    createandloadvideoad()
}

func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
                        didFailToLoadWithError error: Error) {
    print("Reward based video ad failed to load: \(error.localizedDescription)")
    rewardvideoisinprogress = false
}

func rewardBasedVideoAdDidReceive(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
    print("Reward based video ad is received.")
}

func rewardBasedVideoAdDidOpen(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
    print("Opened reward based video ad.")
}

func rewardBasedVideoAdDidStartPlaying(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
    print("Reward based video ad started playing.")
}

func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
    rewardvideoisinprogress = false

    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1500) , execute: {
        print("Brikdsajfaslkd")
        ThemeShop().updatecoins()
    })
}

func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
                        didRewardUserWith reward: GADAdReward) {
    var coins = UserDefaults.standard.integer(forKey: "Coins")
    coins = coins + 50
    UserDefaults.standard.set(coins, forKey: "Coins")  
}

}

这是 SKScene 中的函数:

func updatecoins(){
    print("Updating")
    coins = UserDefaults.standard.integer(forKey: "Coins")
    print("Coins: \(coins)")

    self.coinlabel.text = String(self.coins)
    print(self.coinlabel.text)  
}

我知道硬币正在幕后添加到余额中,因为如果我退出场景并重新进入,硬币就会像它们应该出现的那样出现。

标签: swiftfunctionsprite-kitswift5sklabelnode

解决方案


我认为您的标签没有更新,因为您不在main队列中。我还对您的代码进行了一些更改。你不应该使用sleep()更好的用法asyncAfter

func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
    isRewardVideoInProgress = false

    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        ThemeShop().updatecoins()  
    }
}

func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
                    didRewardUserWith reward: GADAdReward) {
    var coins = UserDefaults.standard.integer(forKey: "Coins")
    coins = coins + 50
    UserDefaults.standard.set(coins, forKey: "Coins")   
}

func updatecoins(){
    print("Updating")
    coins = UserDefaults.standard.integer(forKey: "Coins")
    print("Coins: \(coins)")

    DispatchQueue.main.async {
        self.coinlabel.text = "\(self.coins)"
        print(self.coinlabel.text)  
    }
}

推荐阅读