运行 按下 UIButton 时的功能

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 performSelector:@selector(moveArduinoForward) withObject:nil afterDelay:1]