2017-05-19 1 views
1

내 앱에 맞춤 UIButton을 쓰고 있습니다. 그러나 버튼에 완전한 액션을 추가하고 싶습니다. 이렇게하면 액션에서 BOOL을 반환 한 다음 버튼에서 일부 코드 (예 : 애니메이션 표시)를 실행 한 다음 완료 방법을 호출 할 수 있습니다.커스텀 UIButton에서 TouchUpInside 액션을 호출하는 방법이 있습니까?

따라서, 이상적으로, 나는 이런 식으로 뭔가를 할 수 있도록하고 싶습니다 :

[button addAction:^(){ 
    NSLog(@"Action!"); 
    return true; 
} completion:^() { 
    NSLog(@"Completion!"); 
    return true; 
} forControlEvents:UIControlEventTouchUpInside]; 

어떻게 UIControlEventTouchUpInside가 발생했을 때 어떻게되는지 오버라이드 (override) 할을? 또는 그 문제에 대한 다른 controlevent.

+0

합니다. 'UIButton'에만 국한된 것은 아닙니다. 애플 검색은 당황 스럽기 때문에 빨리 찾을 수 없거나 붙여 넣을 수는 없지만 올바른 방향으로 안내 할 것입니다. –

답변

0

당신은 몇 가지 같은 작업을 수행하여이를 달성 할 수있다 : 당신이 필요로하는 정보는`UIControl` 참조/프로그래밍 가이드에

CustomButton.h

@interface CustomButton : UIButton 
- (void)addAction:(void (^)(CustomButton *button))action onCompletion:(void (^)(CustomButton *button))completion forControlEvents:(UIControlEvents)event; 
@end 

CustomButton.m

#import "CustomButton.h" 

@interface CustomButton() 

@property (nonatomic, copy) void(^actionHandler)(CustomButton *button); 
@property (nonatomic, copy) void(^completionHandler)(CustomButton *button); 

@end 

@implementation CustomButton 

/* 
// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect { 
    // Drawing code 
} 
*/ 



- (void)addAction:(void (^)(CustomButton *button))action onCompletion:(void (^)(CustomButton *button))completion forControlEvents:(UIControlEvents)event 
{ 
    self.actionHandler = action; 
    self.completionHandler = completion; 

    __weak __typeof__(self) weakSelf = self; 
    [self addTarget:weakSelf action:@selector(buttonAction) forControlEvents:event]; 
} 

- (void)buttonAction 
{ 
    if (self.actionHandler) { 
     self.actionHandler(self); 
    } 

    // This will execute right after executing action handler. 
    // NOTE: If action handler is dispatching task, then execution of completionHandler will not wait for completion of dispatched task 
    //  that should handled using some notification/kvo. 
    if (self.completionHandler) { 
     self.completionHandler(self); 
    } 
} 


@end 
관련 문제