2015-03-04 14 views
0

Я создаю автомобиль с дистанционным управлением, используя мой iPhone в качестве контроллера.Функция запуска при нажатии UIButton

Я построил простую кнопку, как показано ниже:

-(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 один раз, когда палец касается кнопки. Я бы хотел, чтобы он постоянно стрелял. Я пробовал несколько способов сделать это безрезультатно, какие-то мысли?

+0

Не уверен, что это хорошая идея, но вы пробовали использовать повторяющуюся '' NSTimer' на touchBegan', а затем на 'touchEnded' недействительным таймер? В этом случае таймер должен вызвать метод обратного вызова кнопки, который выполняет эту работу. – Zhang

ответ

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]

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]; 
} 
Смежные вопросы