26

I've got a simple custom UIButton, to which I added:

button.layer.bordercolor = [[UIColor blueColor]CGColor];

However, I want to change the .bordercolor when the button is highlighted. I tried adding an action to the button's touchDown action that changes the .bordercolor to red, but when the user lifts their finger, it stays red rather than returning to blue. Any ideas?

TylerH
  • 20,799
  • 66
  • 75
  • 101
JohnWickham
  • 571
  • 1
  • 6
  • 15

6 Answers6

46

You were on the right track. Check the code below, it elaborates on this, but what you'll want to do is link selectors to different control events on your button. One for touchDown to change the shadow to red, and another for touchUpInside to change the shadow back when you lift your finger.

Additionally, I see you've asked several questions on Stack Overflow and have yet to mark any as the correct answer. To continue to receive help on this website, you will need to start marking correct answers to your questions.

[myButton addTarget:self action:@selector(highlightBorder) forControlEvents:UIControlEventTouchDown];
[myButton addTarget:self action:@selector(unhighlightBorder) forControlEvents:UIControlEventTouchUpInside];


- (void)highlightBorder
{
    myButton.layer.borderColor = [[UIColor redColor]CGColor];
}

- (void)unhighlightBorder
{
    myButton.layer.borderColor = [[UIColor blueColor]CGColor];
    //additional code for an action when the button is released can go here.
}

NOTE: Other options for UIControlEvents include:

enum {
   UIControlEventTouchDown           = 1 <<  0,
   UIControlEventTouchDownRepeat     = 1 <<  1,
   UIControlEventTouchDragInside     = 1 <<  2,
   UIControlEventTouchDragOutside    = 1 <<  3,
   UIControlEventTouchDragEnter      = 1 <<  4,
   UIControlEventTouchDragExit       = 1 <<  5,
   UIControlEventTouchUpInside       = 1 <<  6,
   UIControlEventTouchUpOutside      = 1 <<  7,
   UIControlEventTouchCancel         = 1 <<  8,

   UIControlEventValueChanged        = 1 << 12,

   UIControlEventEditingDidBegin     = 1 << 16,
   UIControlEventEditingChanged      = 1 << 17,
   UIControlEventEditingDidEnd       = 1 << 18,
   UIControlEventEditingDidEndOnExit = 1 << 19,

   UIControlEventAllTouchEvents      = 0x00000FFF,
   UIControlEventAllEditingEvents    = 0x000F0000,
   UIControlEventApplicationReserved = 0x0F000000,
   UIControlEventSystemReserved      = 0xF0000000,
   UIControlEventAllEvents           = 0xFFFFFFFF
};
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • 1
    Thanks, this works very well if the button receives the touch up inside action, however what if the user were to cancel the touch by dragging their finger off the button? Any idea how I could handle that? Thanks again! – JohnWickham Aug 14 '12 at 06:00
  • 1
    @JohnWickham sure, there's another touch event called touchDragOutside that would probably do the trick. – Mick MacCallum Aug 14 '12 at 12:07
  • to handle dragging outside, I find that this works: [button addTarget:self action:@selector(unhighlightBorder) forControlEvents:UIControlEventTouchCancel]; – cohen72 Jan 12 '14 at 16:49
  • To handle dragging outside, use UIControlEventTouchDragExit – Mikhail Sep 22 '15 at 08:30
17

The SWIFT 2.x answer to your problem:

➜ Just override the highlighted property with "didSet" observer.

override var highlighted: Bool {
    didSet {

        switch highlighted {
        case true:
            layer.borderColor = UIColor.lightGrayColor().CGColor
        case false:
            layer.borderColor = UIColor.blackColor().CGColor
        }
    }
}

Swift 3:

override var isHighlighted: Bool {
    didSet {

        switch isHighlighted {
        case true:
            layer.borderColor = UIColor.lightGray.cgColor
        case false:
            layer.borderColor = UIColor.black.cgColor
        }
    }
}
chengsam
  • 7,315
  • 6
  • 30
  • 38
user3378170
  • 2,371
  • 22
  • 11
9

You can override setHighlighted and setSelected methods in UIButton subclass. From there you just tweak border color like following:

- (void)setHighlighted:(BOOL)highlighted {

    [super setHighlighted:highlighted];

    [self tweakState:highlighted];
}

- (void)setSelected:(BOOL)selected {

    [super setSelected:selected];

    [self tweakState:selected];
}

- (void)tweakState:(BOOL)state {

    if (state) {
        self.layer.borderColor = [_highlightedBorderColor CGColor];
    }
    else {
        self.layer.borderColor = [_defaultBorderColor CGColor];
    }
}
Josip B.
  • 2,434
  • 1
  • 25
  • 30
5

Swift 4 :

override var isHighlighted: Bool {
    didSet {
        layer.borderColor = isHighlighted ? UIColor.lightGray.cgColor : UIColor.black.cgColor
    }
}
fethica
  • 759
  • 6
  • 10
2

Self contained solution:

static UIColor *BorderColor()
{
  return [UIColor grayColor];
}

static UIColor *HighlightedBorderColor()
{
  return [UIColor lightGrayColor];
}

@interface BorderedButton : UIButton

@end

@implementation BorderedButton

- (instancetype)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self) {
    self.layer.borderColor = BorderColor().CGColor;
    self.layer.cornerRadius = 4.0;
    self.layer.borderWidth = 1.0;
  }
  return self;
}

- (void)setHighlighted:(BOOL)highlighted
{
  [super setHighlighted:highlighted];
  self.layer.borderColor = (highlighted) ? HighlightedBorderColor().CGColor : BorderColor().CGColor;
}

@end

Thanks to @josip-b!

Zorayr
  • 23,770
  • 8
  • 136
  • 129
1

For a solution that doesn't involve subclassing, you could always add an extension method to UIButton. E.g.

func setBackgroundColor(_ backgroundColor: UIColor,
                        borderColor: UIColor,
                        borderWidth: CGFloat,
                        cornerRadius: CGFloat,
                        forState state: UIControlState) {

    UIGraphicsBeginImageContext(bounds.size)
    guard let context = UIGraphicsGetCurrentContext() else { return }

    if borderWidth > 0 {
        layer.borderWidth = 0 // hide the layer's border if we're going to draw a border
    }

    context.addPath(UIBezierPath(roundedRect: bounds.insetBy(dx: borderWidth, dy: borderWidth), cornerRadius: cornerRadius).cgPath)
    context.setStrokeColor(borderColor.cgColor)
    context.setFillColor(backgroundColor.cgColor)
    context.setLineWidth(borderWidth)

    context.closePath()
    context.strokePath()
    context.fillPath()

    let buttonImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    setBackgroundImage(buttonImage, for: state)
}
Elijah
  • 8,381
  • 2
  • 55
  • 49
0xWood
  • 1,326
  • 12
  • 15
  • Just bare in mind you'll need to handle redrawing on bounds changes – 0xWood Dec 05 '17 at 12:44
  • See here for SWFIT button observer syntax: https://stackoverflow.com/questions/40272274/how-to-change-bordercolor-when-button-ishighlighted – Ing. Ron Nov 30 '19 at 20:48