[英]Run function while UIButton is pressed
我正在使用iPhone作为控制器来建造遥控车。
我建立了一个简单的按钮,如下所示:
-(void)moveArduinoForward
{
UInt8 buf[3] = {0x01, 0x00, 0x00};
buf[1] = 50;
buf[2] = (int)num >> 8;
NSData *data = [[NSData alloc] initWithBytes:buf length:3];
[self.bleShield write:data];
}
-(void)stopArduino
{
UInt8 buf[3] = {0x05, 0x00, 0x00};
buf[1] = 50;
buf[2] = (int)num >> 8;
NSData *data = [[NSData alloc] initWithBytes:buf length:3];
[self.bleShield write:data];
}
self.moveForwardButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.moveForwardButton.frame = CGRectMake(430.0, 175.0, 117.0, 133.0);
[self.moveForwardButton setImage:[UIImage imageNamed:@"fwdUp.png"] forState:UIControlStateNormal];
[self.moveForwardButton setImage:[UIImage imageNamed:@"fwdDown.png"] forState:UIControlStateHighlighted];
[self.moveForwardButton addTarget:self action:@selector(moveArduinoForward) forControlEvents:UIControlEventTouchDown];
[self.moveForwardButton addTarget:self action:@selector(stopArduino) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
[self.view addSubview:self.moveForwardButton];
这目前无法正常运行。 当手指触摸按钮时,它仅触发一次moveArduinoForward事件。 我希望它不断开火。 我已经尝试了多种方法,但没有用,有什么想法吗?
您可以通过使用计时器来实现。
在.h或.m文件中声明一个计时器,例如:
NSTimer *timer;
并实现您的方法,例如:
// This method will be called when timer is fired
- (void)timerFired
{
UInt8 buf[3] = {0x01, 0x00, 0x00};
buf[1] = 50;
buf[2] = (int)num >> 8;
NSData *data = [[NSData alloc] initWithBytes:buf length:3];
[self.bleShield write:data];
}
// This method schedules the timer
-(void)moveArduinoForward
{
// You can change the time interval as you need
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}
// This method invalidates the timer, when you took your finger off from button
-(void)stopArduino
{
[timer invalidate];
timer = nil;
UInt8 buf[3] = {0x05, 0x00, 0x00};
buf[1] = 50;
buf[2] = (int)num >> 8;
NSData *data = [[NSData alloc] initWithBytes:buf length:3];
[self.bleShield write:data];
}
在没有NSTimer的情况下执行此操作的一种方法是,如果仍然按下该按钮,则只是获得再次调用自身的方法。 使用计时器可能会使您动摇不定。
- (void)moveArduinoForward
{
UInt8 buf[3] = {0x01, 0x00, 0x00};
buf[1] = 50;
buf[2] = (int)num >> 8;
NSData *data = [[NSData alloc] initWithBytes:buf length:3];
[self.bleShield write:data];
if (self.moveForwardButton.isHighlighted) {
[self moveArduinoForward];
}
}
isHighlighted / isSelected。 我想可以用。
如果需要延迟,可以将[self moveArduinoForward]
行替换为[self moveArduinoForward]
[self performSelector:@selector(moveArduinoForward) withObject:nil afterDelay:1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.