【问题标题】:how to detect touchesbegan touchesended for UIBarButtonItem?如何检测 UIBarButtonItem 的 touchesbegan touchesended?
【发布时间】:2011-11-13 22:02:27
【问题描述】:

我正在使用 UIBarButtonItem 来触发事件。我使用 xcode4 中的集成 InterfaceBuider 来创建我的 UIBarButtonItem,然后我将按钮连接到我的视图控制器中的一个方法。该方法如下所示:

-(IBAction)NoteOnOff:(id)sender
{
    UIButton *button = (UIButton*)sender;

   /* now perform action */
}

现在我还想检测 fingerdown/fingerup,因为我想为 midi 合成器类型的应用触发 noteon/noteoff 类型的事件。

1- 有没有办法检测上述方法中sender是被按下还是被按下?

2- 我尝试继承 UIBarButtonItem 并以这种方式实现 touchesBegan 和 touchesEnded:

@interface myUIBarButtonItem : UIBarButtonItem {

}

@end

@implementation myUIBarButtonItem

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesBegan");
NSLog(@"touches=%@,event=%@",touches,event);
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesEnded");
NSLog(@"touches=%@,event=%@",touches,event);
}

@end

然后我在界面编辑器中将 UIBarButtonItem 的类更改为 myUIBarButtonItem 但没有运气。这是在界面编辑器中使用我的自定义类的正确方法吗?

3- 我在某处读到 UIBarButtonItem 没有从 UIResponder 继承,因此它们无法拦截 touchesbegan/touchesended 事件。如果是这种情况,那么能够检测触地和触地事件的正确方法是什么?我主要是一名 C/C++ 程序员,我对目标 C 和 iphone 环境的了解非常有限。我只知道如何使用 UI 编辑器,我不知道如何创建自定义 UI 并在没有此编辑器的情况下使用它们。

底线是:以尽可能少的延迟检测 touchdown/touchup 的最简单方法是什么?

也欢迎任何指向教程或文档的指针。

谢谢,

爸爸

【问题讨论】:

    标签: ios touchesbegan


    【解决方案1】:

    你可以这样做(无需继承 UIBarButtonItem):

    [button addTarget:self action:@selector(touchUp:)
      forControlEvents:UIControlEventTouchUpInside];
    
    [button addTarget:self action:@selector(touchDown:)
      forControlEvents:UIControlEventTouchDown];
    
    - (void) touchUp:(id)sender {
    }
    
    - (void) touchDown:(id)sender {
    }
    

    【讨论】:

    • 谢谢迈克尔,这看起来正是我所需要的。但有一件事是我不知道如何访问button,因为它是在 IB 中创建的。
    • 我试图以这种方式在我的 viewcontroller.h 中声明一个 IBOutlet: IBOutlet UIBarButtonItem *myButton;然后从 IB 链接到该行代码,然后在 viewdidload 中调用 [myButton addTarget ....] 但我得到如下运行时错误: -[UIBarButtonItem addTarget:action:forControlEvents:]: unrecognized selector sent to实例 *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[UIBarButtonItem addTarget:action:forControlEvents:]:无法识别的选择器发送到实例 *** 首次抛出调用堆栈:我错过了什么?谢谢
    • 那是因为 addTarget:action:forControlEvents: 在 UIControl 中声明,而 UIBarButtonItem 没有从 UIControl 继承。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多