如何更改其他课程的按钮图像?

时间:2017-10-31 10:07:35

标签: swift button sprite-kit imagebutton

我是编码新手,我想知道如何从设置类中更改菜单类中的buton图像。

这是菜单类:

class Mainmenu: SKScene{

 var ratingButton = SKSpriteNode(imageNamed: "RatingButton1")
}

在我的设置类中,我想通过单击按钮将此图像更改为“RatingButton2”。

以下是设置类:

class Settings: SKScene {

override func didMove(to view: SKView) {

 self.backgroundColor = SKColor.white

 let DCButton = SKSpriteNode(imageNamed: "ChangeButton")
 DCButton.position = CGPoint(x: self.size.width * 0.2, y: self.size.height * 0.8)
 DCButton.setScale(0.53)
 self.addChild(DCButton)
 }

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches{

        let locationUser = touch.location(in: self)

        if atPoint(locationUser) == DCButton {

        //Change the button image here

        }
      }
    }
  }

2 个答案:

答案 0 :(得分:0)

Swift 3 + 使用Notificationcenter更新按钮图片。

//定义标识符

let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification in Mainmenu
NotificationCenter.default.addObserver(self, selector: #selector(receivedNotification), name: notificationName, object: nil)


// Post notification into Settings write this line into "touchesBegan" method
NotificationCenter.default.post(name: notificationName, object: nil)


// Stop listening notification if required.
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

通知处理程序

func receivedNotification(notification: Notification){
   // Set your button image here...
}

答案 1 :(得分:0)

我不建议使用NSNotificationCenter来完成这项任务,它会为很少使用的东西增加很多开销。

现在很遗憾,我不知道你的布局是如何构建的,所以我不确定哪种答案最适合你。

如果菜单和设置同时在场景中,则您可以搜索场景以找到您要查找的按钮:

class Mainmenu: SKScene{

    var ratingButton = SKSpriteNode(imageNamed: "RatingButton1")
    ratingButton.name = "ratingButton"

}

class Settings: SKScene {

    override func didMove(to view: SKView) {

        self.backgroundColor = SKColor.white

        let DCButton = SKSpriteNode(imageNamed: "ChangeButton")
        DCButton.position = CGPoint(x: self.size.width * 0.2, y: self.size.height * 0.8)
        DCButton.setScale(0.53)
        self.addChild(DCButton)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches{
            let locationUser = touch.location(in: self)
            if atPoint(locationUser) == DCButton {
                let button = scene.childNode(withName:"//ratingButton") as! SKSpriteNode
                button.texture = SKTexture(imageNamed:"RatingButton2")
            }
        }
    }
}

如果它不在现场并且您正在展示它,那么您希望使用userData指定您的按钮之前的内容

let menu = Mainmenu(...)
menu.userData = ["ratingButton":SKTexture(imageNamed:textureName)] //texture name is either Ratingbutton1 or RatingButton2 depending on state
self.view.presentScene(menu)

然后在viewDidLoad中,阅读userData

func viewDidLoad(...)
{
    ratingButton.texture = userData?["ratingButton"]

}