2

在我的小应用程序中,用户单击“ON”按钮,然后我调用一个带有 while 循环的方法,并且应该出现“OFF”按钮,但是我的“OFF”按钮没有出现。

-(void) myMethod{

    while (_onButton.selected) {

        [self vibrate];
         NSLog(@"working");
    } 
}


- (IBAction)on:(id)sender {

    _offButton.hidden=NO;
    _offButton.selected=NO;
    _onButton.hidden=YES;
    _onButton.selected=YES;

       [self myMethod];


}

- (IBAction)off:(id)sender {

    _onButton.hidden=NO;
    _offButton.hidden=YES;
    _onButton.selected=NO;
    _offButton.selected=YES;
}
4

2 回答 2

0

这是一个无限循环伴侣。像这样更改while循环:

while (_onButton.selected) {

[self vibrate];
 NSLog(@"working");
_onButton.selected = NO;
}

或 while (_onButton.selected) {

[self vibrate];
 NSLog(@"working");
break;
}
于 2013-02-23T10:27:14.770 回答
0

当您使用此循环时:

while (_onButton.selected) {

    [self vibrate];
     NSLog(@"working");
} 

您不允许运行循环处理新事件,因此按钮将永远没有机会更改状态(因为它不会接收来自用户的触摸)。这是非常糟糕的,你不应该这样做。

而是通过使用在选择按钮时一直持续的声音委托方法继续振动(您没有显示如何执行振动,因此我无法在此处提供更多详细信息)。

编辑在 OP 发表评论后:

- (void)vibrate
{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} 

好的,AudioServices 提供了一个“完成程序”,通过AudioServicesAddSystemSoundCompletion()它可以让您在选择按钮时重放振动“声音”。使用这种机制而不是while循环。

于 2013-02-23T10:28:37.953 回答