簡體   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