Skip to content

Instantly share code, notes, and snippets.

@tvervest
Created January 30, 2014 13:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvervest/8708465 to your computer and use it in GitHub Desktop.
Save tvervest/8708465 to your computer and use it in GitHub Desktop.
A drop-in replacement for the UIBarButtonItem class which passes the set target and action to the custom view if it is a UIControl. As I grew tired of having to pay attention to UIBarButtonItem objects having custom (control) views, I wrote an extending class which actually behaves the way (I think) the parent class should. All you have to do is…
//
// ExtendedBarButtonItem.h
//
// Created by Thomas Vervest.
// This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
// http://creativecommons.org/licenses/by-sa/4.0/
//
#import <UIKit/UIKit.h>
@interface ExtendedBarButtonItem : UIBarButtonItem
@end
//
// ExtendedBarButtonItem.m
//
// Created by Thomas Vervest.
// This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
// http://creativecommons.org/licenses/by-sa/4.0/
//
#import "ExtendedBarButtonItem.h"
@implementation ExtendedBarButtonItem
- (void)setAction:(SEL)action
{
if (!action)
{
[self removeControlTarget];
}
[super setAction:action];
if (action)
{
[self updateControlTarget];
}
}
- (void)setTarget:(id)target
{
if (!target)
{
[self removeControlTarget];
}
[super setTarget:target];
if (target)
{
[self updateControlTarget];
}
}
- (void)removeControlTarget
{
if (self.target && self.action && [self.customView isKindOfClass:[UIControl class]])
{
UIControl *control = (UIButton*)self.customView;
[control removeTarget:self.target
action:self.action
forControlEvents:UIControlEventTouchUpInside];
}
}
- (void)updateControlTarget
{
if (self.target && self.action && [self.customView isKindOfClass:[UIControl class]])
{
UIControl *control = (UIButton*)self.customView;
[control addTarget:self.target
action:self.action
forControlEvents:UIControlEventTouchUpInside];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment