开发者

Call a method from UIButton subclass @implementation

I work on a project for iPhone iOS 4 with Xcode 4.

I have subclassed a UIButton so that it intercepts single and double tap.

This is the final part of @implementation of the UIButton subclass, two instance methods where the taps are "r开发者_StackOverflowecorded";

 - (void) handleTap: (UITapGestureRecognizer *) sender {
     NSLog(@"single tap");
 }

 - (void) handleDoubleTap :(UITapGestureRecognizer *) sender {
     NSLog(@"double tap");
 }

A button instance is created in nib and all works OK: it intercepts single tap and double tap and output the NSLog.

Now the question: I have in my ViewController two methods (resetAllFields and populateAllFields) and I need that single tap execute resetAllFields and double tap execute populateAllFields.

How can I do? Where do I put the call?

Thank you.


If you want to handle the behavior in the ViewController the typical solution is to add a @protocol in your custom button class that defines methods for handling the single and double taps.

i.e. in your CustomButton.h

@protocol CustomButtonDelegate <NSObject>
    - (void)button:(CustomButton *)button tappedWithCount:(int)count;
@end

You then have a delegate that implements this protocol in your custom button class and call those methods on the delegate when your taps are detected.

i.e. in your CustomButton.h

id <CustomButtonDelegate> _delegate;

in your methods in the implementation:

- (void) handleTap: (UITapGestureRecognizer *) sender {
   NSLog(@"single tap");
   [self.delegate button:self tappedWithCount:1];
}

- (void) handleDoubleTap :(UITapGestureRecognizer *) sender {
   NSLog(@"double tap");
   [self.delegate button:self tappedWithCount:2];
}

Your View Controller than implements the protocol methods and sets itself as the custom button's delegate.

ie. in your ViewControllers implementation

- (void)button:(CustomButton *)button tappedWithCount:(int)count {
     if (count == 1) {
         [self resetAllFields];
     } else if (count == 2) {
         [self populateAllFields];
     }
}

Since you are using Interface Builder to set the custom button you can assign your view controller as a delegate in there or in the ViewDidLoad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜