我在Objective-C中有一个UIButton,如果按钮在10秒之前松开,我想取消按下。我该怎么做?
提前致谢
答案 0 :(得分:3)
您可以使用以下内容:
[yourButton addGestureRecognizer:[[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handle:)]];
创建一个名为timer的NSTimer属性:
@property (nonatomic, strong) NSTimer *timer;
还有一个柜台:
@property (nonatomic, strong) int counter;
- (void)incrementCounter {
self.counter++;
}
- (void)handle:(UILongPressGestureRecognizer)gesture {
if (gesture.state == UIGestureRecognizerStateBegan) {
self.counter = 0;
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(incrementCounter) userInfo:nil repeats:yes];
}
if (gesture.state == UIGestureRecognizerStateEnded) {
[self.timer invalidate];
}
}
因此,当手势开始时,启动一个计时器,每秒触发一次增量方法,直到手势结束。在这种情况下,您需要将minimumPressDuration设置为0,否则手势将不会立即开始。 通过这种方式,您可以获得计时器并在按下按钮时使用self.counter = 10秒。
如果有帮助,请告诉我。
答案 1 :(得分:2)
为了坚持使用UIButton
的预期设计,我建议您使用UIButton
的{{1}}和UIControlEventTouchUpInside
控制事件。
(提示:UIControlEventTouchDown
方法)
-addTarget:action:forControlEvents:
UIControlEventTouchDown
UIControlEventTouchUpInside
操作方法中
UIControlEventTouchUpInside
UIButton *btnTest;
NSTimer *tmrTest;
int i_tmrCount;
- (void)viewDidLoad
{
//...
i_tmrCount = 0;
btnTest = [UIButton buttonWithType:UIButtonTypeCustom];
[btnTest setFrame:CGRectMake(20, 100, 100, 30)];
[btnTest setTitle:@"Test" forState:UIControlStateNormal];
//method connected to the button pressed down event alone
[btnTest addTarget:self action:@selector(btnTestActStart:)
forControlEvents:UIControlEventTouchDown];
//method connected to the button pressed down and released event
[btnTest addTarget:self action:@selector(btnTestAct:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTest];
}
- (void)btnTestActStart:(UIButton *)sender
{
tmrTest = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(timerDo)
userInfo:nil
repeats:YES];
}
-(void)timerDo
{
i_tmrCount++;
}
PS:如果是- (void)btnTestAct:(UIButton *)sender
{
//stop the timer
[tmrTest invalidate];
if (i_tmrCount >= 10) {
//do something
NSLog(@"action");
} else {
//do nothing
NSLog(@"reset");
}
//reset i_tmrCount to initial state (to handle next occurrence)
i_tmrCount = 0;
}
,那么请使用UILabel
,但对于UILongPressGestureRecognizer
,它将不理想,因为您必须删除连接到按钮UIButton
的方法的实现,而是将方法连接到UIControlEventTouchUpInside
作为主按钮方法(感觉有点脏)