在Swift中点击时如何更改button的BGColour

我是iOS新手(Swift)。 你能告诉我如何改变一个button的背景颜色,当它被轻按/按下。 代码必须在Swift中。 我尝试了,但我无法find解决scheme

我假设你正在使用Storyboard。

您可以从Button拖放到viewController:

然后在“连接”中select“操作”
把它命名为你想要的。 (在“tapMe”的例子中)
然后在“types”中selectUIButton
按连接。

你应该有这样的东西:

@IBAction func tapMe(sender: UIButton) { print("I'm tapped") sender.backgroundColor = UIColor.greenColor() } 

很多颜色可供select:

 public class func blackColor() -> UIColor // 0.0 white public class func darkGrayColor() -> UIColor // 0.333 white public class func lightGrayColor() -> UIColor // 0.667 white public class func whiteColor() -> UIColor // 1.0 white public class func grayColor() -> UIColor // 0.5 white public class func redColor() -> UIColor // 1.0, 0.0, 0.0 RGB public class func greenColor() -> UIColor // 0.0, 1.0, 0.0 RGB public class func blueColor() -> UIColor // 0.0, 0.0, 1.0 RGB public class func cyanColor() -> UIColor // 0.0, 1.0, 1.0 RGB public class func yellowColor() -> UIColor // 1.0, 1.0, 0.0 RGB public class func magentaColor() -> UIColor // 1.0, 0.0, 1.0 RGB public class func orangeColor() -> UIColor // 1.0, 0.5, 0.0 RGB public class func purpleColor() -> UIColor // 0.5, 0.0, 0.5 RGB public class func brownColor() -> UIColor // 0.6, 0.4, 0.2 RGB 

好的回答papay0。 还有另一种方法,根据你的需要,可能会更好。 你可以在视图控制器的viewDidLoad中使用像myButton.setBackgroundColor(UIColor.blueColor(), forState: UIControlState.Selected) 。 我不知道你的确切的应用程序,所以你可能想在这里使用Apple文档中的许多控制状态:

 Declaration SWIFT struct UIControlState : OptionSetType { init(rawValue rawValue: UInt) static var Normal: UIControlState { get } static var Highlighted: UIControlState { get } static var Disabled: UIControlState { get } static var Selected: UIControlState { get } static var Focused: UIControlState { get } static var Application: UIControlState { get } static var Reserved: UIControlState { get } } OBJECTIVE-C typedef NSUInteger UIControlState; 

希望这可以帮助! 如果你有问题,请告诉我。