Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NghiaTranUIT/32f33e26cae4f149719e to your computer and use it in GitHub Desktop.
Save NghiaTranUIT/32f33e26cae4f149719e to your computer and use it in GitHub Desktop.
// Add catefory
@interface UIButton (Sound)
@end
#import "UIButton+Sound.h"
#import <objc/runtime.h>
@implementation UIButton (Sound)
+(void) load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self exchangeSendAction];
});
}
+(void) exchangeSendAction
{
Class class = [self class];
SEL originalSelector = @selector(sendAction:to:forEvent:);
SEL swizzleSelector = @selector(swizzle_SendAction:to:forEvent:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzleMethod = class_getInstanceMethod(class, swizzleSelector);
BOOL isSuccess = class_addMethod(class, originalSelector, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
if (isSuccess)
{
class_replaceMethod(class, swizzleSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else
{
method_exchangeImplementations(originalMethod, swizzleMethod);
}
}
-(void) swizzle_SendAction:(SEL)action to:(nullable id)target forEvent:(nullable UIEvent *)event
{
// Hack here
NSLog(@"implement your sound here");
// Forward to primary implementation.
[self swizzle_SendAction:action to:target forEvent:event];
}
////// In your controller
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_topBtn = [UIButton buttonWithType:UIButtonTypeSystem];
[_topBtn setTitle:@"Top Button" forState:UIControlStateNormal];
[_topBtn addTarget:self action:@selector(topBtnTapped) forControlEvents:UIControlEventTouchUpInside];
_topBtn.titleLabel.textColor = [UIColor blackColor];
[_topBtn sizeToFit];
_topBtn.center = CGPointMake(self.view.center.x, 200);
[self.view addSubview:_topBtn];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)centerBtnTapped:(id)sender // from Storyboard
{
NSLog(@"Center Btn Tapped");
}
-(void) topBtnTapped
{
NSLog(@"Top Btn Tapped");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment