从UIButton子类@implementation调用一个方法

时间:2011-08-15 17:24:23

标签: iphone ios4 call

我使用Xcode 4为iPhone iOS 4开发项目。

我已经将UIButton子类化,因此它可以拦截单击和双击。

这是UIButton子类的@implementation的最后一部分,两个实例方法,其中“记录”了水龙头;

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

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

在nib中创建一个按钮实例,所有工作正常:它拦截单击并双击并输出NSLog。

现在的问题是:我在我的ViewController中有两个方法(resetAllFields和populateAllFields),我需要单击执行resetAllFields并双击执行populateAllFields。

我该怎么办?我在哪里拨打电话?

谢谢。

1 个答案:

答案 0 :(得分:2)

如果要处理ViewController中的行为,典型的解决方案是在自定义按钮类中添加@protocol,定义处理单击和双击的方法。

即。在您的CustomButton.h中

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

然后,您有一个委托,在您的自定义按钮类中实现此协议,并在检测到点按时在代理上调用这些方法。

即。在您的CustomButton.h中

id <CustomButtonDelegate> _delegate;

在您的实现方法中:

- (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];
}

您的View Controller比实现协议方法并将其自身设置为自定义按钮的委托。

即。在ViewControllers实现中

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

由于您使用Interface Builder设置自定义按钮,因此您可以将视图控制器指定为其中或ViewDidLoad中的委托。

相关问题