Swift UIButton background change on OnTouchUp and OnTouchDown?

人走茶凉 提交于 2019-12-25 03:44:28

问题


I am using swift and in my app there is a UIButton, for which I want to change background color and border color on key down and key up.


回答1:


You can just create two functions and connect them to appropriate events. Like this:

@IBAction func up(){
    myButton.backgroundColor = UIColor.whiteColor()
}

@IBAction func down(){
    myButton.backgroundColor = UIColor.blackColor()
}

Now just connect them in interface builder. Function up() connect to Touch Up Inside and Touch Up Outside. Function down() to Touch Down.

But theres is a better way, take your button and in code set his background image for state.

//this will show when button is released
myButton.setBackgroundImage(UIImage(named:"background_image_normal"), forState:UIControlState.Normal)

//this will show when button is pressed
myButton.setBackgroundImage(UIImage(named:"background_image_highlighted"), forState:UIControlState.Highlighted)



回答2:


In Xcode, in your storyboard, check the "Utilities" panel in the right side, then click on the "Show the Attributes Inspector" is the one that looks like an arrow down, when your button is selected there is the "State Config" panel to choose which state you want to customize, change it to "Highlighted" then change background image, default image, etc...



来源:https://stackoverflow.com/questions/28875055/swift-uibutton-background-change-on-ontouchup-and-ontouchdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!