2014-11-05 59 views
0

我们需要设置一个UIButton有2种方法,第一种是当你触摸它(向下和向上),你会得到一个动作,但是当你长按它,你就会得到一个又一个。UIButton的两种方法?

例如,要获得关于它的数据,当你长按,当常规的点击,另一件事。

哪能用的UIButton实现这一目标?

  UIButton *CAT = [UIButton buttonWithType:UIButtonTypeCustom]; 
      CAT.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter; 
      CAT.backgroundColor=[UIColor clearColor]; 
      [CAT addTarget:self action:@selector(newcat:)forControlEvents:UIControlEventTouchUpInside]; 

我已经开始用这个

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)]; 
     [CAT addGestureRecognizer:longPress]; 

增加它的姿态,但这种触发只有当你脱下你的手指。 我希望在1-2秒后我的手指仍然在那里时被触发。 我可以这样做吗?我可以调整触发所需的时间吗?

+0

我的直觉是将UIButton子类化,并使用'NSTimer'和以下信息添加长按和短按事件:https://developer.apple.com/library/ios/documentation/uikit/reference /uicontrol_class/index.html#//apple_ref/doc/constant_group/Control_Events – nburk 2014-11-05 09:42:16

+0

感谢了很多,看到我的编辑,它的实际工作,但并不如预期 – Curnelious 2014-11-05 09:43:44

回答

0

这是正常的方法

 UIButton *CAT = [UIButton buttonWithType:UIButtonTypeCustom]; 
     CAT.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter; 
     CAT.backgroundColor=[UIColor clearColor]; 
     [CAT addTarget:self action:@selector(newcat:)forControlEvents:UIControlEventTouchUpInside]; 



UILongPressGestureRecognizer *longpressGesture = 
[[UILongPressGestureRecognizer alloc] initWithTarget:self 
             action:@selector(longPressHandler:)]; 
longpressGesture.minimumPressDuration = 5; // set the time interval 

[longpressGesture setDelegate:self]; 
[CAT addGestureRecognizer:longpressGesture]; 

[self.view addsubview: CAT]; 

长按动作方法

- (void)longPressHandler:(UILongPressGestureRecognizer *)gestureRecognizer { 
NSLog(@"longPressHandler"); 
// do long press action 
} 

正常动作方法

-(void) newcat:(id)sender 

{ 
    // do normal action here 
} 
+0

//定制乌尔自我 – 2014-11-05 09:46:18

+0

感谢为我写我这样做,但问题在于,只有当你将手指从屏幕上移开时,才会发生长按,我希望在1秒钟后手指仍然在那里时,手指会发出长鸣。 – Curnelious 2014-11-05 09:47:14

+0

好的,我解决它,谢谢。 – Curnelious 2014-11-05 09:53:49

1

您可以使用事件UIControlEventTouchDown,使用延迟时间长按,你必须处理UIControlEventTouchUpInsideUIControlEventTouchUpOutside。祝你好运!