在OnTouchUp和OnTouchDown的Swift UIButton背景更改?

我使用的是swift,在我的应用程序中有一个UIButton,为此我想在键上改变背景颜色和边框颜色。

您可以创build两个函数并将它们连接到适当的事件。 喜欢这个:

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

现在只需在界面生成器中连接它们。 functionup()连接到Touch Up Inside和Touch Up Outside。 按下function()触按。

但是,这是一个更好的方法,拿你的button,在代码中设置他的背景图像的状态。

 //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) 

在Xcode中,在你的故事板中,勾选右侧的“Utilities”面板,然后点击“Show the Attributes Inspector”就是一个向下的箭头,当你的button被选中时,会出现“State Config”面板来select你想要定制的状态,将其改为“突出显示”,然后更改背景图像,默认图像等。