问题
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