从其他View Controller-Swift 4.2更改UIButton的状态

时间:2019-02-28 00:35:43

标签: uibutton game-center appdelegate swift4.2

我在VC1中有gameCenterButton。其目的是将用户带到游戏中心的排行榜,在这里可以看到高分。如果用户决定通过Game Center进行身份验证,那么我想更改gameCenterButton的状态(不灰色并启用)。在我的GameKitHelper班上,我有以下这些东西:

func authenticateLocalPlayer() {

    GKLocalPlayer.local.authenticateHandler =
        { (viewController, error) in

            self.gameCenterEnabled = false
            if viewController != nil {

                self.authenticationViewController = viewController
                NotificationCenter.default.post(name: NSNotification.Name(
                    GameKitHelper.PresentAuthenticationViewController),
                                                object: self)
            } else if GKLocalPlayer.local.isAuthenticated {

                self.gameCenterEnabled = true
            }
    }
}

extension GameKitHelper: GKGameCenterControllerDelegate {
func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
    gameCenterViewController.dismiss(animated: true, completion: nil)

    }
}

在VC1中,我有这个:

@IBOutlet weak var gameCenterButton: UIButton!

@IBAction func gameCenter(_ sender: UIButton) {

    GameKitHelper.sharedInstance.showGKGameCenterViewController(viewController: self)

}

我认为在extension GameKitHelper内部我可以做...

if gameCenterEnabled == true {

    gameCenterButton.isEnabled = true  // How do I allow for this?

    gameCenterButton.alpha = 1  // How do I allow for this?

如何允许gameCenterButton状态在其类之外进行更改。在AppDelegate中我需要做些什么吗?

1 个答案:

答案 0 :(得分:1)

var gameCenterEnabled = false放在GameKitHelper类的外面(上方),从而使其成为“全局”。可能会提示您删除self.self.gameCenterEnabled = false中的self.gameCenterEnabled = true。这样做。

现在,您可以在gameCenterEnabled的类中引用VC1并按以下方式更改gameCenterButton的状态:

        // code to determine gameCenterButton's state based on gameCenterEnabled's status
        if gameCenterEnabled == false {

            self.gameCenterButton.isEnabled = false
            self.gameCenterButton.alpha = 0.37  
        } else {
            self.gameCenterButton.isEnabled = true
            self.gameCenterButton.alpha = 1
        }