Raghavendra Poluri
Raghavendra Poluri

Reputation: 1

How to change BGColour of button when tapped in Swift

I'm new to iOS(Swift). Can you please tell me how to change background colour of a button when it is tapped/pressed. The code must be in Swift. I tried, but I'm not able to find the solution

Upvotes: 0

Views: 129

Answers (2)

PyPiePi
PyPiePi

Reputation: 253

Good answer papay0. There is another way as well that, depending on what you need, might be better. You can use something like myButton.setBackgroundColor(UIColor.blueColor(), forState: UIControlState.Selected) in the viewDidLoad of your view controller. I don't know your exact application, so you might want to use any of the numerous control states in the Apple Documentation here:

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;

Hope this helps! Let me know if you have questions.

Upvotes: 0

papay0
papay0

Reputation: 1311

I assume you are using Storyboard.

You can drag and drop from the Button to the viewController:

Then select Action in "Connection"
Name it whatever you want. (In the example "tapMe")
Then select UIButton in "Type"
Press Connect.

You should have something like:

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

A lot of colours are available:

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 

Upvotes: 1

Related Questions