【问题标题】:I want to change the image of the button as long as user taps on the button?只要用户点击按钮,我就想更改按钮的图像?
【发布时间】:2017-11-10 19:17:05
【问题描述】:

只要用户点击按钮,我想更改按钮的图像,但如果他从屏幕上松开手指,则将图像更改回原始图像(我正在使用 Sprite-Kit)

我的代码:

var SettingButton = SKSpriteNode(imageNamed: "SettingButton1.0")

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {    
    for touch in touches{
        let locationUser = touch.location(in: self)

        if atPoint(locationUser) == SettingButton{
            let SettingButton = SKSpriteNode(imageNamed: "SettingButton2.0") //change the image
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches{ 
        let locationUser = touch.location(in: self)

        if atPoint(locationUser) == SettingButton{
            //change image back to original
        }
    }
}

【问题讨论】:

  • 您的问题是什么?你的代码编译了吗?您是否收到运行时错误?您的代码没有按照您的预期执行?请更具体。
  • 我不知道如何在 touchesBegan 函数@Dávid Pásztor 中通过上面的按钮更改图像

标签: swift sprite-kit imagebutton


【解决方案1】:

尝试交换 SpriteNode 的纹理

var buttonTextureUp = SKTexture(imageNamed: "SettingButton1.0")
var buttonTextureDown = SKTexture(imageNamed: "SettingButton2.0")

var settingButton = SKSpriteNode(texture: buttonTextureUp)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {    
    for touch in touches{
        let locationUser = touch.location(in: self)

        if atPoint(locationUser) == settingButton {
            settingButton.texture = buttonTextureDown //change the image
        }
    }
}

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

    for touch in touches{ 
        let locationUser = touch.location(in: self)

        if atPoint(locationUser) == settingButton{
            settingButton.texture = buttonTextureUp //change image back to original
        }
    }
}

【讨论】:

  • 如果 touchesCancelled 被调用,不要忘记将纹理更改为 buttonTexture up
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-04-17
相关资源
最近更新 更多