How do I set UIButton background color forState: UIControlState.Highlighted in Swift












38















I can set the background color for a button but I can't work out how to set the background color for UIControlState.Highlighted. Is it even possible? or do I need to go down the setBackgroundImage path?










share|improve this question

























  • Check this post somethingaboutios.wordpress.com/2016/02/09/… Swift example at the end of the post.

    – Gabriel.Massana
    Feb 9 '16 at 21:03
















38















I can set the background color for a button but I can't work out how to set the background color for UIControlState.Highlighted. Is it even possible? or do I need to go down the setBackgroundImage path?










share|improve this question

























  • Check this post somethingaboutios.wordpress.com/2016/02/09/… Swift example at the end of the post.

    – Gabriel.Massana
    Feb 9 '16 at 21:03














38












38








38


11






I can set the background color for a button but I can't work out how to set the background color for UIControlState.Highlighted. Is it even possible? or do I need to go down the setBackgroundImage path?










share|improve this question
















I can set the background color for a button but I can't work out how to set the background color for UIControlState.Highlighted. Is it even possible? or do I need to go down the setBackgroundImage path?







ios swift uibutton xcode6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 2 '15 at 19:29









winterized

2,55631420




2,55631420










asked Oct 28 '14 at 4:37









David WoodDavid Wood

6042713




6042713













  • Check this post somethingaboutios.wordpress.com/2016/02/09/… Swift example at the end of the post.

    – Gabriel.Massana
    Feb 9 '16 at 21:03



















  • Check this post somethingaboutios.wordpress.com/2016/02/09/… Swift example at the end of the post.

    – Gabriel.Massana
    Feb 9 '16 at 21:03

















Check this post somethingaboutios.wordpress.com/2016/02/09/… Swift example at the end of the post.

– Gabriel.Massana
Feb 9 '16 at 21:03





Check this post somethingaboutios.wordpress.com/2016/02/09/… Swift example at the end of the post.

– Gabriel.Massana
Feb 9 '16 at 21:03












9 Answers
9






active

oldest

votes


















102














If anyone stops by, another way to go maybe more easily if it is something you need more than once... I wrote a short extension for UIButton, it works just fine:



for Swift 3



extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

self.setBackgroundImage(colorImage, forState: forState)
}
}


for Swift 4



extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControl.State) {
self.clipsToBounds = true // add this to maintain corner radius
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}
}
}


You use it just like setBackgroundImage:



yourButton.setBackgroundColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)





share|improve this answer





















  • 9





    This will destroy auto layout and remove corner radius.

    – user4788711
    Jun 17 '15 at 17:08






  • 1





    @ user4788711 just as setting a background image would. Not more, not less.

    – winterized
    Jun 23 '15 at 15:42






  • 1





    works perfectly!

    – CularBytes
    Jul 16 '15 at 15:18






  • 11





    in order to fix corner radius you just need to enable Clip subviews on button

    – heximal
    Sep 12 '15 at 20:58






  • 2





    For me, it was totally worth it to extend UIImage with an initializer for the color part. Then this function's body becomes simply self.setBackgroundImage(UIImage(color: color), forState: forState)

    – Phlippie Bosman
    Sep 5 '17 at 9:44



















32














Syntax changes to @winterized extension for Swift 3+ syntax



extension UIButton {
func setBackgroundColor(color: UIColor, forState: UIControlState) {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: forState)
}}





share|improve this answer

































    15














    Below will be one way to go. Two IBActions. One to control background color when depressing a button, one on release.



    import UIKit

    class ViewController: UIViewController {


    @IBOutlet weak var button: UIButton!

    @IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
    button.backgroundColor = UIColor.whiteColor()
    }

    @IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
    button.backgroundColor = UIColor.blueColor()

    }

    override func viewDidLoad() {
    super.viewDidLoad()

    }
    }


    When you look at the autocomplete options for your button after adding a period, you can set a background color, but not for specified state. You can only set background images. Now of course if you are married to doing it this way instead of using the method I show above, you could load an image of the desired color as the background image using the setbackgroundImageForState property.



    enter image description here



    enter image description here






    share|improve this answer


























    • That's going to work perfectly! Thanks!

      – David Wood
      Oct 28 '14 at 8:30






    • 1





      That solution works only in a ViewController but not in a TableViewController. The touched down action works also in TVC but only with some miliseconds delay, sothat a fast touch on screen won't change color of button. I think there's somewhere a problem with the cell in which the button is, but i'm not sure.

      – S. Birklin
      Jun 11 '15 at 11:44











    • I ran exactly in the same problem. If I only tap the view than nothing happens because the color is already back to the old color. I could fix this problem with a little delay so that the color is switched back some milliseconds later. So the color is visible even if the user only taps shortly.

      – Philipp Otto
      Aug 19 '15 at 15:49











    • Also, I think the "Touch Down" method is risky. First, it doesn't reset the color automatically. That's easy enough, on "Touch-up Inside" just set it back to the original color. But what if the user does something abnormal, like pushes down, then decides not to continue, and drags their finger off. The color won't reset.

      – Dave G
      Jan 2 '16 at 22:56



















    4














    Swift 4 Version of this solution:



    extension UIButton {

    func setBackgroundColor(_ color: UIColor, for state: UIControlState) {

    UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
    UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
    UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    setBackgroundImage(colorImage, for: state)
    }
    }





    share|improve this answer



















    • 2





      Just a small improvement to the code, to avoid force-unwraps try doing this: if let currentGraphicsContext = UIGraphicsGetCurrentContext() { currentGraphicsContext.setFillColor(color.cgColor) currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } Plus adding layer.masksToBounds = true to keep the functionality of layer.cornerRadius

      – T. Hyldgaard
      Jan 24 '18 at 13:41





















    4














    Update Swift 4



     extension UIButton {

    func setBackgroundColor(color: UIColor, forState: UIControlState) {

    UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
    UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
    UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()


    self.setBackgroundImage(colorImage, for: forState)
    }


    Event
    Button Action



    Show Touch On Hightlight






    share|improve this answer

































      2














      Seems nobody here has mentioned using Key Value Observation yet, but it's another approach.



      A reason for doing so instead of picking the other answers here is you don't need to go creating new images all the time nor be concerned with secondary effects of assigning images to buttons (e.g. cornerRadius effects).



      But you'll need to create a class for the observer, who would be responsible for storing the different background colours and applying them in the observeValue() method.



      public class ButtonHighlighterObserver: NSObject {

      var observedButton:UIButton? = nil

      var backgroundColor: UIColor = UIColor.white
      var backgroundHighlightColor: UIColor = UIColor.gray

      public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

      // Perform background color changes when highlight state change is observed
      if keyPath == "highlighted", object as? UIButton === observedButton {
      observedButton!.backgroundColor = observedButton!.isHighlighted ? self.backgroundHighlightColor : self.backgroundColor
      }
      }


      }



      Then all you need to do is manage addObserver / removeObserver during operation:



      // Add observer to button's highlighted value
      button.addObserver(anObserver, forKeyPath: "highlighted", options: [.new], context: nil)
      anObserver.observedButton = button

      // ...

      // And at deinit time, be sure you remove the observer again
      anObserver.observedButton?.removeObserver(item, forKeyPath: "highlighted")
      anObserver.observedButton = nil





      share|improve this answer































        1














        Can we do the same using run time attributes?



        @IBInspectable var HighlightedBackground: Bool {
        get {
        return true
        }
        set {
        layer.backgroundColor = Common.sharedInstance.OrangeColor.CGColor
        print("highlighted state")
        }
        }





        share|improve this answer

































          1














          Why not?



          @implementation UIButton (Color)

          - (void) setBackgroundColor:(UIColor*)color forState:(UIControlState)state
          {
          [self setBackgroundImage:[UIImage.alloc initWithCIImage:[CIImage imageWithColor:[CIColor colorWithCGColor:color.CGColor]]] forState:state];
          }

          @end





          share|improve this answer

































            1














            Swift 4+ compatibility for the accepted answer :



            extension UIButton {

            /// Sets the background color to use for the specified button state.
            func setBackgroundColor(color: UIColor, forState: UIControlState) {

            let minimumSize: CGSize = CGSize(width: 1.0, height: 1.0)

            UIGraphicsBeginImageContext(minimumSize)

            if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(origin: .zero, size: minimumSize))
            }

            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            self.clipsToBounds = true
            self.setBackgroundImage(colorImage, for: forState)
            }
            }


            Compatible SwiftLint and fix the bug of broken auto layout / corner radius.






            share|improve this answer


























            • Or you can change your button type to system instead of custom

              – Maximelc
              Sep 19 '18 at 12:12











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26600980%2fhow-do-i-set-uibutton-background-color-forstate-uicontrolstate-highlighted-in-s%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            9 Answers
            9






            active

            oldest

            votes








            9 Answers
            9






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            102














            If anyone stops by, another way to go maybe more easily if it is something you need more than once... I wrote a short extension for UIButton, it works just fine:



            for Swift 3



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControlState) {
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
            CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            self.setBackgroundImage(colorImage, forState: forState)
            }
            }


            for Swift 4



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControl.State) {
            self.clipsToBounds = true // add this to maintain corner radius
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
            }
            }
            }


            You use it just like setBackgroundImage:



            yourButton.setBackgroundColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)





            share|improve this answer





















            • 9





              This will destroy auto layout and remove corner radius.

              – user4788711
              Jun 17 '15 at 17:08






            • 1





              @ user4788711 just as setting a background image would. Not more, not less.

              – winterized
              Jun 23 '15 at 15:42






            • 1





              works perfectly!

              – CularBytes
              Jul 16 '15 at 15:18






            • 11





              in order to fix corner radius you just need to enable Clip subviews on button

              – heximal
              Sep 12 '15 at 20:58






            • 2





              For me, it was totally worth it to extend UIImage with an initializer for the color part. Then this function's body becomes simply self.setBackgroundImage(UIImage(color: color), forState: forState)

              – Phlippie Bosman
              Sep 5 '17 at 9:44
















            102














            If anyone stops by, another way to go maybe more easily if it is something you need more than once... I wrote a short extension for UIButton, it works just fine:



            for Swift 3



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControlState) {
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
            CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            self.setBackgroundImage(colorImage, forState: forState)
            }
            }


            for Swift 4



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControl.State) {
            self.clipsToBounds = true // add this to maintain corner radius
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
            }
            }
            }


            You use it just like setBackgroundImage:



            yourButton.setBackgroundColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)





            share|improve this answer





















            • 9





              This will destroy auto layout and remove corner radius.

              – user4788711
              Jun 17 '15 at 17:08






            • 1





              @ user4788711 just as setting a background image would. Not more, not less.

              – winterized
              Jun 23 '15 at 15:42






            • 1





              works perfectly!

              – CularBytes
              Jul 16 '15 at 15:18






            • 11





              in order to fix corner radius you just need to enable Clip subviews on button

              – heximal
              Sep 12 '15 at 20:58






            • 2





              For me, it was totally worth it to extend UIImage with an initializer for the color part. Then this function's body becomes simply self.setBackgroundImage(UIImage(color: color), forState: forState)

              – Phlippie Bosman
              Sep 5 '17 at 9:44














            102












            102








            102







            If anyone stops by, another way to go maybe more easily if it is something you need more than once... I wrote a short extension for UIButton, it works just fine:



            for Swift 3



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControlState) {
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
            CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            self.setBackgroundImage(colorImage, forState: forState)
            }
            }


            for Swift 4



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControl.State) {
            self.clipsToBounds = true // add this to maintain corner radius
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
            }
            }
            }


            You use it just like setBackgroundImage:



            yourButton.setBackgroundColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)





            share|improve this answer















            If anyone stops by, another way to go maybe more easily if it is something you need more than once... I wrote a short extension for UIButton, it works just fine:



            for Swift 3



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControlState) {
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor)
            CGContextFillRect(UIGraphicsGetCurrentContext(), CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            self.setBackgroundImage(colorImage, forState: forState)
            }
            }


            for Swift 4



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControl.State) {
            self.clipsToBounds = true // add this to maintain corner radius
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(color.cgColor)
            context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
            }
            }
            }


            You use it just like setBackgroundImage:



            yourButton.setBackgroundColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 19 '18 at 20:12









            Quinn

            40612




            40612










            answered Jun 2 '15 at 19:13









            winterizedwinterized

            2,55631420




            2,55631420








            • 9





              This will destroy auto layout and remove corner radius.

              – user4788711
              Jun 17 '15 at 17:08






            • 1





              @ user4788711 just as setting a background image would. Not more, not less.

              – winterized
              Jun 23 '15 at 15:42






            • 1





              works perfectly!

              – CularBytes
              Jul 16 '15 at 15:18






            • 11





              in order to fix corner radius you just need to enable Clip subviews on button

              – heximal
              Sep 12 '15 at 20:58






            • 2





              For me, it was totally worth it to extend UIImage with an initializer for the color part. Then this function's body becomes simply self.setBackgroundImage(UIImage(color: color), forState: forState)

              – Phlippie Bosman
              Sep 5 '17 at 9:44














            • 9





              This will destroy auto layout and remove corner radius.

              – user4788711
              Jun 17 '15 at 17:08






            • 1





              @ user4788711 just as setting a background image would. Not more, not less.

              – winterized
              Jun 23 '15 at 15:42






            • 1





              works perfectly!

              – CularBytes
              Jul 16 '15 at 15:18






            • 11





              in order to fix corner radius you just need to enable Clip subviews on button

              – heximal
              Sep 12 '15 at 20:58






            • 2





              For me, it was totally worth it to extend UIImage with an initializer for the color part. Then this function's body becomes simply self.setBackgroundImage(UIImage(color: color), forState: forState)

              – Phlippie Bosman
              Sep 5 '17 at 9:44








            9




            9





            This will destroy auto layout and remove corner radius.

            – user4788711
            Jun 17 '15 at 17:08





            This will destroy auto layout and remove corner radius.

            – user4788711
            Jun 17 '15 at 17:08




            1




            1





            @ user4788711 just as setting a background image would. Not more, not less.

            – winterized
            Jun 23 '15 at 15:42





            @ user4788711 just as setting a background image would. Not more, not less.

            – winterized
            Jun 23 '15 at 15:42




            1




            1





            works perfectly!

            – CularBytes
            Jul 16 '15 at 15:18





            works perfectly!

            – CularBytes
            Jul 16 '15 at 15:18




            11




            11





            in order to fix corner radius you just need to enable Clip subviews on button

            – heximal
            Sep 12 '15 at 20:58





            in order to fix corner radius you just need to enable Clip subviews on button

            – heximal
            Sep 12 '15 at 20:58




            2




            2





            For me, it was totally worth it to extend UIImage with an initializer for the color part. Then this function's body becomes simply self.setBackgroundImage(UIImage(color: color), forState: forState)

            – Phlippie Bosman
            Sep 5 '17 at 9:44





            For me, it was totally worth it to extend UIImage with an initializer for the color part. Then this function's body becomes simply self.setBackgroundImage(UIImage(color: color), forState: forState)

            – Phlippie Bosman
            Sep 5 '17 at 9:44













            32














            Syntax changes to @winterized extension for Swift 3+ syntax



            extension UIButton {
            func setBackgroundColor(color: UIColor, forState: UIControlState) {
            UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
            UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
            UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
            let colorImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            self.setBackgroundImage(colorImage, for: forState)
            }}





            share|improve this answer






























              32














              Syntax changes to @winterized extension for Swift 3+ syntax



              extension UIButton {
              func setBackgroundColor(color: UIColor, forState: UIControlState) {
              UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
              UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
              UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
              let colorImage = UIGraphicsGetImageFromCurrentImageContext()
              UIGraphicsEndImageContext()
              self.setBackgroundImage(colorImage, for: forState)
              }}





              share|improve this answer




























                32












                32








                32







                Syntax changes to @winterized extension for Swift 3+ syntax



                extension UIButton {
                func setBackgroundColor(color: UIColor, forState: UIControlState) {
                UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                self.setBackgroundImage(colorImage, for: forState)
                }}





                share|improve this answer















                Syntax changes to @winterized extension for Swift 3+ syntax



                extension UIButton {
                func setBackgroundColor(color: UIColor, forState: UIControlState) {
                UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                self.setBackgroundImage(colorImage, for: forState)
                }}






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 30 '18 at 4:36

























                answered Oct 5 '16 at 8:15









                MaverickMaverick

                1,75411629




                1,75411629























                    15














                    Below will be one way to go. Two IBActions. One to control background color when depressing a button, one on release.



                    import UIKit

                    class ViewController: UIViewController {


                    @IBOutlet weak var button: UIButton!

                    @IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
                    button.backgroundColor = UIColor.whiteColor()
                    }

                    @IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
                    button.backgroundColor = UIColor.blueColor()

                    }

                    override func viewDidLoad() {
                    super.viewDidLoad()

                    }
                    }


                    When you look at the autocomplete options for your button after adding a period, you can set a background color, but not for specified state. You can only set background images. Now of course if you are married to doing it this way instead of using the method I show above, you could load an image of the desired color as the background image using the setbackgroundImageForState property.



                    enter image description here



                    enter image description here






                    share|improve this answer


























                    • That's going to work perfectly! Thanks!

                      – David Wood
                      Oct 28 '14 at 8:30






                    • 1





                      That solution works only in a ViewController but not in a TableViewController. The touched down action works also in TVC but only with some miliseconds delay, sothat a fast touch on screen won't change color of button. I think there's somewhere a problem with the cell in which the button is, but i'm not sure.

                      – S. Birklin
                      Jun 11 '15 at 11:44











                    • I ran exactly in the same problem. If I only tap the view than nothing happens because the color is already back to the old color. I could fix this problem with a little delay so that the color is switched back some milliseconds later. So the color is visible even if the user only taps shortly.

                      – Philipp Otto
                      Aug 19 '15 at 15:49











                    • Also, I think the "Touch Down" method is risky. First, it doesn't reset the color automatically. That's easy enough, on "Touch-up Inside" just set it back to the original color. But what if the user does something abnormal, like pushes down, then decides not to continue, and drags their finger off. The color won't reset.

                      – Dave G
                      Jan 2 '16 at 22:56
















                    15














                    Below will be one way to go. Two IBActions. One to control background color when depressing a button, one on release.



                    import UIKit

                    class ViewController: UIViewController {


                    @IBOutlet weak var button: UIButton!

                    @IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
                    button.backgroundColor = UIColor.whiteColor()
                    }

                    @IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
                    button.backgroundColor = UIColor.blueColor()

                    }

                    override func viewDidLoad() {
                    super.viewDidLoad()

                    }
                    }


                    When you look at the autocomplete options for your button after adding a period, you can set a background color, but not for specified state. You can only set background images. Now of course if you are married to doing it this way instead of using the method I show above, you could load an image of the desired color as the background image using the setbackgroundImageForState property.



                    enter image description here



                    enter image description here






                    share|improve this answer


























                    • That's going to work perfectly! Thanks!

                      – David Wood
                      Oct 28 '14 at 8:30






                    • 1





                      That solution works only in a ViewController but not in a TableViewController. The touched down action works also in TVC but only with some miliseconds delay, sothat a fast touch on screen won't change color of button. I think there's somewhere a problem with the cell in which the button is, but i'm not sure.

                      – S. Birklin
                      Jun 11 '15 at 11:44











                    • I ran exactly in the same problem. If I only tap the view than nothing happens because the color is already back to the old color. I could fix this problem with a little delay so that the color is switched back some milliseconds later. So the color is visible even if the user only taps shortly.

                      – Philipp Otto
                      Aug 19 '15 at 15:49











                    • Also, I think the "Touch Down" method is risky. First, it doesn't reset the color automatically. That's easy enough, on "Touch-up Inside" just set it back to the original color. But what if the user does something abnormal, like pushes down, then decides not to continue, and drags their finger off. The color won't reset.

                      – Dave G
                      Jan 2 '16 at 22:56














                    15












                    15








                    15







                    Below will be one way to go. Two IBActions. One to control background color when depressing a button, one on release.



                    import UIKit

                    class ViewController: UIViewController {


                    @IBOutlet weak var button: UIButton!

                    @IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
                    button.backgroundColor = UIColor.whiteColor()
                    }

                    @IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
                    button.backgroundColor = UIColor.blueColor()

                    }

                    override func viewDidLoad() {
                    super.viewDidLoad()

                    }
                    }


                    When you look at the autocomplete options for your button after adding a period, you can set a background color, but not for specified state. You can only set background images. Now of course if you are married to doing it this way instead of using the method I show above, you could load an image of the desired color as the background image using the setbackgroundImageForState property.



                    enter image description here



                    enter image description here






                    share|improve this answer















                    Below will be one way to go. Two IBActions. One to control background color when depressing a button, one on release.



                    import UIKit

                    class ViewController: UIViewController {


                    @IBOutlet weak var button: UIButton!

                    @IBAction func buttonClicked(sender: AnyObject) { //Touch Up Inside action
                    button.backgroundColor = UIColor.whiteColor()
                    }

                    @IBAction func buttonReleased(sender: AnyObject) { //Touch Down action
                    button.backgroundColor = UIColor.blueColor()

                    }

                    override func viewDidLoad() {
                    super.viewDidLoad()

                    }
                    }


                    When you look at the autocomplete options for your button after adding a period, you can set a background color, but not for specified state. You can only set background images. Now of course if you are married to doing it this way instead of using the method I show above, you could load an image of the desired color as the background image using the setbackgroundImageForState property.



                    enter image description here



                    enter image description here







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Oct 28 '14 at 5:26

























                    answered Oct 28 '14 at 5:17









                    Steve RosenbergSteve Rosenberg

                    14.9k63949




                    14.9k63949













                    • That's going to work perfectly! Thanks!

                      – David Wood
                      Oct 28 '14 at 8:30






                    • 1





                      That solution works only in a ViewController but not in a TableViewController. The touched down action works also in TVC but only with some miliseconds delay, sothat a fast touch on screen won't change color of button. I think there's somewhere a problem with the cell in which the button is, but i'm not sure.

                      – S. Birklin
                      Jun 11 '15 at 11:44











                    • I ran exactly in the same problem. If I only tap the view than nothing happens because the color is already back to the old color. I could fix this problem with a little delay so that the color is switched back some milliseconds later. So the color is visible even if the user only taps shortly.

                      – Philipp Otto
                      Aug 19 '15 at 15:49











                    • Also, I think the "Touch Down" method is risky. First, it doesn't reset the color automatically. That's easy enough, on "Touch-up Inside" just set it back to the original color. But what if the user does something abnormal, like pushes down, then decides not to continue, and drags their finger off. The color won't reset.

                      – Dave G
                      Jan 2 '16 at 22:56



















                    • That's going to work perfectly! Thanks!

                      – David Wood
                      Oct 28 '14 at 8:30






                    • 1





                      That solution works only in a ViewController but not in a TableViewController. The touched down action works also in TVC but only with some miliseconds delay, sothat a fast touch on screen won't change color of button. I think there's somewhere a problem with the cell in which the button is, but i'm not sure.

                      – S. Birklin
                      Jun 11 '15 at 11:44











                    • I ran exactly in the same problem. If I only tap the view than nothing happens because the color is already back to the old color. I could fix this problem with a little delay so that the color is switched back some milliseconds later. So the color is visible even if the user only taps shortly.

                      – Philipp Otto
                      Aug 19 '15 at 15:49











                    • Also, I think the "Touch Down" method is risky. First, it doesn't reset the color automatically. That's easy enough, on "Touch-up Inside" just set it back to the original color. But what if the user does something abnormal, like pushes down, then decides not to continue, and drags their finger off. The color won't reset.

                      – Dave G
                      Jan 2 '16 at 22:56

















                    That's going to work perfectly! Thanks!

                    – David Wood
                    Oct 28 '14 at 8:30





                    That's going to work perfectly! Thanks!

                    – David Wood
                    Oct 28 '14 at 8:30




                    1




                    1





                    That solution works only in a ViewController but not in a TableViewController. The touched down action works also in TVC but only with some miliseconds delay, sothat a fast touch on screen won't change color of button. I think there's somewhere a problem with the cell in which the button is, but i'm not sure.

                    – S. Birklin
                    Jun 11 '15 at 11:44





                    That solution works only in a ViewController but not in a TableViewController. The touched down action works also in TVC but only with some miliseconds delay, sothat a fast touch on screen won't change color of button. I think there's somewhere a problem with the cell in which the button is, but i'm not sure.

                    – S. Birklin
                    Jun 11 '15 at 11:44













                    I ran exactly in the same problem. If I only tap the view than nothing happens because the color is already back to the old color. I could fix this problem with a little delay so that the color is switched back some milliseconds later. So the color is visible even if the user only taps shortly.

                    – Philipp Otto
                    Aug 19 '15 at 15:49





                    I ran exactly in the same problem. If I only tap the view than nothing happens because the color is already back to the old color. I could fix this problem with a little delay so that the color is switched back some milliseconds later. So the color is visible even if the user only taps shortly.

                    – Philipp Otto
                    Aug 19 '15 at 15:49













                    Also, I think the "Touch Down" method is risky. First, it doesn't reset the color automatically. That's easy enough, on "Touch-up Inside" just set it back to the original color. But what if the user does something abnormal, like pushes down, then decides not to continue, and drags their finger off. The color won't reset.

                    – Dave G
                    Jan 2 '16 at 22:56





                    Also, I think the "Touch Down" method is risky. First, it doesn't reset the color automatically. That's easy enough, on "Touch-up Inside" just set it back to the original color. But what if the user does something abnormal, like pushes down, then decides not to continue, and drags their finger off. The color won't reset.

                    – Dave G
                    Jan 2 '16 at 22:56











                    4














                    Swift 4 Version of this solution:



                    extension UIButton {

                    func setBackgroundColor(_ color: UIColor, for state: UIControlState) {

                    UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                    UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                    UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()

                    setBackgroundImage(colorImage, for: state)
                    }
                    }





                    share|improve this answer



















                    • 2





                      Just a small improvement to the code, to avoid force-unwraps try doing this: if let currentGraphicsContext = UIGraphicsGetCurrentContext() { currentGraphicsContext.setFillColor(color.cgColor) currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } Plus adding layer.masksToBounds = true to keep the functionality of layer.cornerRadius

                      – T. Hyldgaard
                      Jan 24 '18 at 13:41


















                    4














                    Swift 4 Version of this solution:



                    extension UIButton {

                    func setBackgroundColor(_ color: UIColor, for state: UIControlState) {

                    UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                    UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                    UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()

                    setBackgroundImage(colorImage, for: state)
                    }
                    }





                    share|improve this answer



















                    • 2





                      Just a small improvement to the code, to avoid force-unwraps try doing this: if let currentGraphicsContext = UIGraphicsGetCurrentContext() { currentGraphicsContext.setFillColor(color.cgColor) currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } Plus adding layer.masksToBounds = true to keep the functionality of layer.cornerRadius

                      – T. Hyldgaard
                      Jan 24 '18 at 13:41
















                    4












                    4








                    4







                    Swift 4 Version of this solution:



                    extension UIButton {

                    func setBackgroundColor(_ color: UIColor, for state: UIControlState) {

                    UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                    UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                    UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()

                    setBackgroundImage(colorImage, for: state)
                    }
                    }





                    share|improve this answer













                    Swift 4 Version of this solution:



                    extension UIButton {

                    func setBackgroundColor(_ color: UIColor, for state: UIControlState) {

                    UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                    UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                    UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()

                    setBackgroundImage(colorImage, for: state)
                    }
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 20 '17 at 15:58









                    kaktusgruenkaktusgruen

                    826




                    826








                    • 2





                      Just a small improvement to the code, to avoid force-unwraps try doing this: if let currentGraphicsContext = UIGraphicsGetCurrentContext() { currentGraphicsContext.setFillColor(color.cgColor) currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } Plus adding layer.masksToBounds = true to keep the functionality of layer.cornerRadius

                      – T. Hyldgaard
                      Jan 24 '18 at 13:41
















                    • 2





                      Just a small improvement to the code, to avoid force-unwraps try doing this: if let currentGraphicsContext = UIGraphicsGetCurrentContext() { currentGraphicsContext.setFillColor(color.cgColor) currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } Plus adding layer.masksToBounds = true to keep the functionality of layer.cornerRadius

                      – T. Hyldgaard
                      Jan 24 '18 at 13:41










                    2




                    2





                    Just a small improvement to the code, to avoid force-unwraps try doing this: if let currentGraphicsContext = UIGraphicsGetCurrentContext() { currentGraphicsContext.setFillColor(color.cgColor) currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } Plus adding layer.masksToBounds = true to keep the functionality of layer.cornerRadius

                    – T. Hyldgaard
                    Jan 24 '18 at 13:41







                    Just a small improvement to the code, to avoid force-unwraps try doing this: if let currentGraphicsContext = UIGraphicsGetCurrentContext() { currentGraphicsContext.setFillColor(color.cgColor) currentGraphicsContext.fill(CGRect(x: 0, y: 0, width: 1, height: 1)) } Plus adding layer.masksToBounds = true to keep the functionality of layer.cornerRadius

                    – T. Hyldgaard
                    Jan 24 '18 at 13:41













                    4














                    Update Swift 4



                     extension UIButton {

                    func setBackgroundColor(color: UIColor, forState: UIControlState) {

                    UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                    UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                    UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()


                    self.setBackgroundImage(colorImage, for: forState)
                    }


                    Event
                    Button Action



                    Show Touch On Hightlight






                    share|improve this answer






























                      4














                      Update Swift 4



                       extension UIButton {

                      func setBackgroundColor(color: UIColor, forState: UIControlState) {

                      UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                      UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                      UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                      let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                      UIGraphicsEndImageContext()


                      self.setBackgroundImage(colorImage, for: forState)
                      }


                      Event
                      Button Action



                      Show Touch On Hightlight






                      share|improve this answer




























                        4












                        4








                        4







                        Update Swift 4



                         extension UIButton {

                        func setBackgroundColor(color: UIColor, forState: UIControlState) {

                        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                        UIGraphicsEndImageContext()


                        self.setBackgroundImage(colorImage, for: forState)
                        }


                        Event
                        Button Action



                        Show Touch On Hightlight






                        share|improve this answer















                        Update Swift 4



                         extension UIButton {

                        func setBackgroundColor(color: UIColor, forState: UIControlState) {

                        UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
                        UIGraphicsGetCurrentContext()!.setFillColor(color.cgColor)
                        UIGraphicsGetCurrentContext()!.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
                        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                        UIGraphicsEndImageContext()


                        self.setBackgroundImage(colorImage, for: forState)
                        }


                        Event
                        Button Action



                        Show Touch On Hightlight







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Apr 11 '18 at 10:56

























                        answered Apr 11 '18 at 9:38









                        Puji WahonoPuji Wahono

                        1137




                        1137























                            2














                            Seems nobody here has mentioned using Key Value Observation yet, but it's another approach.



                            A reason for doing so instead of picking the other answers here is you don't need to go creating new images all the time nor be concerned with secondary effects of assigning images to buttons (e.g. cornerRadius effects).



                            But you'll need to create a class for the observer, who would be responsible for storing the different background colours and applying them in the observeValue() method.



                            public class ButtonHighlighterObserver: NSObject {

                            var observedButton:UIButton? = nil

                            var backgroundColor: UIColor = UIColor.white
                            var backgroundHighlightColor: UIColor = UIColor.gray

                            public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

                            // Perform background color changes when highlight state change is observed
                            if keyPath == "highlighted", object as? UIButton === observedButton {
                            observedButton!.backgroundColor = observedButton!.isHighlighted ? self.backgroundHighlightColor : self.backgroundColor
                            }
                            }


                            }



                            Then all you need to do is manage addObserver / removeObserver during operation:



                            // Add observer to button's highlighted value
                            button.addObserver(anObserver, forKeyPath: "highlighted", options: [.new], context: nil)
                            anObserver.observedButton = button

                            // ...

                            // And at deinit time, be sure you remove the observer again
                            anObserver.observedButton?.removeObserver(item, forKeyPath: "highlighted")
                            anObserver.observedButton = nil





                            share|improve this answer




























                              2














                              Seems nobody here has mentioned using Key Value Observation yet, but it's another approach.



                              A reason for doing so instead of picking the other answers here is you don't need to go creating new images all the time nor be concerned with secondary effects of assigning images to buttons (e.g. cornerRadius effects).



                              But you'll need to create a class for the observer, who would be responsible for storing the different background colours and applying them in the observeValue() method.



                              public class ButtonHighlighterObserver: NSObject {

                              var observedButton:UIButton? = nil

                              var backgroundColor: UIColor = UIColor.white
                              var backgroundHighlightColor: UIColor = UIColor.gray

                              public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

                              // Perform background color changes when highlight state change is observed
                              if keyPath == "highlighted", object as? UIButton === observedButton {
                              observedButton!.backgroundColor = observedButton!.isHighlighted ? self.backgroundHighlightColor : self.backgroundColor
                              }
                              }


                              }



                              Then all you need to do is manage addObserver / removeObserver during operation:



                              // Add observer to button's highlighted value
                              button.addObserver(anObserver, forKeyPath: "highlighted", options: [.new], context: nil)
                              anObserver.observedButton = button

                              // ...

                              // And at deinit time, be sure you remove the observer again
                              anObserver.observedButton?.removeObserver(item, forKeyPath: "highlighted")
                              anObserver.observedButton = nil





                              share|improve this answer


























                                2












                                2








                                2







                                Seems nobody here has mentioned using Key Value Observation yet, but it's another approach.



                                A reason for doing so instead of picking the other answers here is you don't need to go creating new images all the time nor be concerned with secondary effects of assigning images to buttons (e.g. cornerRadius effects).



                                But you'll need to create a class for the observer, who would be responsible for storing the different background colours and applying them in the observeValue() method.



                                public class ButtonHighlighterObserver: NSObject {

                                var observedButton:UIButton? = nil

                                var backgroundColor: UIColor = UIColor.white
                                var backgroundHighlightColor: UIColor = UIColor.gray

                                public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

                                // Perform background color changes when highlight state change is observed
                                if keyPath == "highlighted", object as? UIButton === observedButton {
                                observedButton!.backgroundColor = observedButton!.isHighlighted ? self.backgroundHighlightColor : self.backgroundColor
                                }
                                }


                                }



                                Then all you need to do is manage addObserver / removeObserver during operation:



                                // Add observer to button's highlighted value
                                button.addObserver(anObserver, forKeyPath: "highlighted", options: [.new], context: nil)
                                anObserver.observedButton = button

                                // ...

                                // And at deinit time, be sure you remove the observer again
                                anObserver.observedButton?.removeObserver(item, forKeyPath: "highlighted")
                                anObserver.observedButton = nil





                                share|improve this answer













                                Seems nobody here has mentioned using Key Value Observation yet, but it's another approach.



                                A reason for doing so instead of picking the other answers here is you don't need to go creating new images all the time nor be concerned with secondary effects of assigning images to buttons (e.g. cornerRadius effects).



                                But you'll need to create a class for the observer, who would be responsible for storing the different background colours and applying them in the observeValue() method.



                                public class ButtonHighlighterObserver: NSObject {

                                var observedButton:UIButton? = nil

                                var backgroundColor: UIColor = UIColor.white
                                var backgroundHighlightColor: UIColor = UIColor.gray

                                public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

                                // Perform background color changes when highlight state change is observed
                                if keyPath == "highlighted", object as? UIButton === observedButton {
                                observedButton!.backgroundColor = observedButton!.isHighlighted ? self.backgroundHighlightColor : self.backgroundColor
                                }
                                }


                                }



                                Then all you need to do is manage addObserver / removeObserver during operation:



                                // Add observer to button's highlighted value
                                button.addObserver(anObserver, forKeyPath: "highlighted", options: [.new], context: nil)
                                anObserver.observedButton = button

                                // ...

                                // And at deinit time, be sure you remove the observer again
                                anObserver.observedButton?.removeObserver(item, forKeyPath: "highlighted")
                                anObserver.observedButton = nil






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Feb 14 '18 at 14:41









                                MeteMete

                                3,10622027




                                3,10622027























                                    1














                                    Can we do the same using run time attributes?



                                    @IBInspectable var HighlightedBackground: Bool {
                                    get {
                                    return true
                                    }
                                    set {
                                    layer.backgroundColor = Common.sharedInstance.OrangeColor.CGColor
                                    print("highlighted state")
                                    }
                                    }





                                    share|improve this answer






























                                      1














                                      Can we do the same using run time attributes?



                                      @IBInspectable var HighlightedBackground: Bool {
                                      get {
                                      return true
                                      }
                                      set {
                                      layer.backgroundColor = Common.sharedInstance.OrangeColor.CGColor
                                      print("highlighted state")
                                      }
                                      }





                                      share|improve this answer




























                                        1












                                        1








                                        1







                                        Can we do the same using run time attributes?



                                        @IBInspectable var HighlightedBackground: Bool {
                                        get {
                                        return true
                                        }
                                        set {
                                        layer.backgroundColor = Common.sharedInstance.OrangeColor.CGColor
                                        print("highlighted state")
                                        }
                                        }





                                        share|improve this answer















                                        Can we do the same using run time attributes?



                                        @IBInspectable var HighlightedBackground: Bool {
                                        get {
                                        return true
                                        }
                                        set {
                                        layer.backgroundColor = Common.sharedInstance.OrangeColor.CGColor
                                        print("highlighted state")
                                        }
                                        }






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Nov 16 '15 at 8:38









                                        Manjunath Ballur

                                        4,70732239




                                        4,70732239










                                        answered Nov 16 '15 at 8:00









                                        Sonika SoodSonika Sood

                                        207




                                        207























                                            1














                                            Why not?



                                            @implementation UIButton (Color)

                                            - (void) setBackgroundColor:(UIColor*)color forState:(UIControlState)state
                                            {
                                            [self setBackgroundImage:[UIImage.alloc initWithCIImage:[CIImage imageWithColor:[CIColor colorWithCGColor:color.CGColor]]] forState:state];
                                            }

                                            @end





                                            share|improve this answer






























                                              1














                                              Why not?



                                              @implementation UIButton (Color)

                                              - (void) setBackgroundColor:(UIColor*)color forState:(UIControlState)state
                                              {
                                              [self setBackgroundImage:[UIImage.alloc initWithCIImage:[CIImage imageWithColor:[CIColor colorWithCGColor:color.CGColor]]] forState:state];
                                              }

                                              @end





                                              share|improve this answer




























                                                1












                                                1








                                                1







                                                Why not?



                                                @implementation UIButton (Color)

                                                - (void) setBackgroundColor:(UIColor*)color forState:(UIControlState)state
                                                {
                                                [self setBackgroundImage:[UIImage.alloc initWithCIImage:[CIImage imageWithColor:[CIColor colorWithCGColor:color.CGColor]]] forState:state];
                                                }

                                                @end





                                                share|improve this answer















                                                Why not?



                                                @implementation UIButton (Color)

                                                - (void) setBackgroundColor:(UIColor*)color forState:(UIControlState)state
                                                {
                                                [self setBackgroundImage:[UIImage.alloc initWithCIImage:[CIImage imageWithColor:[CIColor colorWithCGColor:color.CGColor]]] forState:state];
                                                }

                                                @end






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Aug 7 '18 at 12:50

























                                                answered Aug 7 '18 at 10:33









                                                poGUIstpoGUIst

                                                240310




                                                240310























                                                    1














                                                    Swift 4+ compatibility for the accepted answer :



                                                    extension UIButton {

                                                    /// Sets the background color to use for the specified button state.
                                                    func setBackgroundColor(color: UIColor, forState: UIControlState) {

                                                    let minimumSize: CGSize = CGSize(width: 1.0, height: 1.0)

                                                    UIGraphicsBeginImageContext(minimumSize)

                                                    if let context = UIGraphicsGetCurrentContext() {
                                                    context.setFillColor(color.cgColor)
                                                    context.fill(CGRect(origin: .zero, size: minimumSize))
                                                    }

                                                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                                                    UIGraphicsEndImageContext()

                                                    self.clipsToBounds = true
                                                    self.setBackgroundImage(colorImage, for: forState)
                                                    }
                                                    }


                                                    Compatible SwiftLint and fix the bug of broken auto layout / corner radius.






                                                    share|improve this answer


























                                                    • Or you can change your button type to system instead of custom

                                                      – Maximelc
                                                      Sep 19 '18 at 12:12
















                                                    1














                                                    Swift 4+ compatibility for the accepted answer :



                                                    extension UIButton {

                                                    /// Sets the background color to use for the specified button state.
                                                    func setBackgroundColor(color: UIColor, forState: UIControlState) {

                                                    let minimumSize: CGSize = CGSize(width: 1.0, height: 1.0)

                                                    UIGraphicsBeginImageContext(minimumSize)

                                                    if let context = UIGraphicsGetCurrentContext() {
                                                    context.setFillColor(color.cgColor)
                                                    context.fill(CGRect(origin: .zero, size: minimumSize))
                                                    }

                                                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                                                    UIGraphicsEndImageContext()

                                                    self.clipsToBounds = true
                                                    self.setBackgroundImage(colorImage, for: forState)
                                                    }
                                                    }


                                                    Compatible SwiftLint and fix the bug of broken auto layout / corner radius.






                                                    share|improve this answer


























                                                    • Or you can change your button type to system instead of custom

                                                      – Maximelc
                                                      Sep 19 '18 at 12:12














                                                    1












                                                    1








                                                    1







                                                    Swift 4+ compatibility for the accepted answer :



                                                    extension UIButton {

                                                    /// Sets the background color to use for the specified button state.
                                                    func setBackgroundColor(color: UIColor, forState: UIControlState) {

                                                    let minimumSize: CGSize = CGSize(width: 1.0, height: 1.0)

                                                    UIGraphicsBeginImageContext(minimumSize)

                                                    if let context = UIGraphicsGetCurrentContext() {
                                                    context.setFillColor(color.cgColor)
                                                    context.fill(CGRect(origin: .zero, size: minimumSize))
                                                    }

                                                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                                                    UIGraphicsEndImageContext()

                                                    self.clipsToBounds = true
                                                    self.setBackgroundImage(colorImage, for: forState)
                                                    }
                                                    }


                                                    Compatible SwiftLint and fix the bug of broken auto layout / corner radius.






                                                    share|improve this answer















                                                    Swift 4+ compatibility for the accepted answer :



                                                    extension UIButton {

                                                    /// Sets the background color to use for the specified button state.
                                                    func setBackgroundColor(color: UIColor, forState: UIControlState) {

                                                    let minimumSize: CGSize = CGSize(width: 1.0, height: 1.0)

                                                    UIGraphicsBeginImageContext(minimumSize)

                                                    if let context = UIGraphicsGetCurrentContext() {
                                                    context.setFillColor(color.cgColor)
                                                    context.fill(CGRect(origin: .zero, size: minimumSize))
                                                    }

                                                    let colorImage = UIGraphicsGetImageFromCurrentImageContext()
                                                    UIGraphicsEndImageContext()

                                                    self.clipsToBounds = true
                                                    self.setBackgroundImage(colorImage, for: forState)
                                                    }
                                                    }


                                                    Compatible SwiftLint and fix the bug of broken auto layout / corner radius.







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Sep 19 '18 at 14:03

























                                                    answered Sep 19 '18 at 10:42









                                                    MaximelcMaximelc

                                                    9801216




                                                    9801216













                                                    • Or you can change your button type to system instead of custom

                                                      – Maximelc
                                                      Sep 19 '18 at 12:12



















                                                    • Or you can change your button type to system instead of custom

                                                      – Maximelc
                                                      Sep 19 '18 at 12:12

















                                                    Or you can change your button type to system instead of custom

                                                    – Maximelc
                                                    Sep 19 '18 at 12:12





                                                    Or you can change your button type to system instead of custom

                                                    – Maximelc
                                                    Sep 19 '18 at 12:12


















                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26600980%2fhow-do-i-set-uibutton-background-color-forstate-uicontrolstate-highlighted-in-s%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    鏡平學校

                                                    ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

                                                    Guess what letter conforming each word