【问题标题】:Call a method from UIButton subclass @implementation从 UIButton 子类 @implementation 调用方法
【发布时间】:2011-08-15 17:24:22
【问题描述】:

我正在使用 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。

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

谢谢。

【问题讨论】:

    标签: iphone ios4 call


    【解决方案1】:

    如果你想处理 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 中的委托。

    【讨论】:

    • 谢谢。我是新手,所以我需要更多关于委托的解释。如何创建它们?
    • 糟糕,现在我看到了您的完整答案。谢谢。
    • 如何在 viewDidLoad 中声明委托?我试过 [CustomButton setDelegate:self];但收到警告 CustomButton 可能无法响应 setDelegate
    • 该按钮在界面生成器中设置正确吗?如果是这样,那么您可以通过插座获得它。即 self.customButton.delegate = self
    • 另外,请确保为代理设置了@property。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2017-11-09
    • 2011-10-24
    • 1970-01-01
    • 2011-01-05
    相关资源
    最近更新 更多