2017-05-19 77 views
1

我正在爲我的應用程序編寫自定義UIButton。不過,我想向按鈕添加一個完整的操作。這樣我就可以從動作返回BOOL,然後在按鈕中執行一些代碼(即顯示一個動畫),然後調用完成方法。有沒有辦法在自定義UIButton中調用TouchUpInside動作?

所以,理想情況下,我希望能夠做這樣的事情:

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

如何重寫時UIControlEventTouchUpInside時會發生什麼?或者是這個問題的另一種控制。

+0

你需要的信息是'UIControl'參考/編程指南。它不是特定於'UIButton'。蘋果的搜索現在很糟糕,所以我無法快速找到/粘貼任何東西,但這會讓您指向正確的方向。 –

回答

0

你可以做一些像實現這一目標:

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 
相關問題