按下UIButton时运行功能

时间:2015-03-04 03:49:16

标签: ios objective-c iphone uibutton

我正在使用我的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事件一次。我想继续开火。我尝试了多种方法来做到这一点无济于事,还有什么想法?

2 个答案:

答案 0 :(得分:1)

您可以使用计时器实现此目的。

在.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];
}

答案 1 :(得分:0)

在没有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]