繁体   English   中英

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

[英]How to change BGColour of button when tapped in Swift

我是iOS(Swift)的新手。 您能告诉我如何在点击/按下按钮时更改背景颜色。 该代码必须在Swift中。 我尝试过,但是找不到解决方案

我假设您正在使用Storyboard。

您可以从Button拖放到viewController中:

然后在“连接”中选择“操作”
随便命名。 (在示例“ tapMe”中)
然后在“类型”中选择UIButton
按连接。

您应该具有以下内容:

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

有很多颜色可供选择:

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;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM