Ios 为什么我的UIButton有时在按下时不会立即做出反应?

Ios 为什么我的UIButton有时在按下时不会立即做出反应?,ios,uiviewcontroller,uibutton,Ios,Uiviewcontroller,Uibutton,我开发了一个iOS应用程序,它有两个UIButton,但是当我按下按钮时,这些按钮有时似乎会滞后。有时滞后非常严重,有时需要10秒。我几乎可以肯定,这与我正在使用的NSTimer有关。我只想让UIViewController在按下按钮后立即切换,我不希望有任何延迟。这是我的密码: RealTimeModeViewController.m ViewController.m 两个UIButton通过模式样式相互连接到ViewController。也许我应该把按钮放在主线上?我对线程不是很熟悉。谢谢。

我开发了一个iOS应用程序,它有两个UIButton,但是当我按下按钮时,这些按钮有时似乎会滞后。有时滞后非常严重,有时需要10秒。我几乎可以肯定,这与我正在使用的NSTimer有关。我只想让UIViewController在按下按钮后立即切换,我不希望有任何延迟。这是我的密码:

RealTimeModeViewController.m

ViewController.m


两个UIButton通过模式样式相互连接到ViewController。也许我应该把按钮放在主线上?我对线程不是很熟悉。谢谢。

如果非要我猜的话,你在UpdateTime:方法中做了一些耗时的事情。因为它位于主线程上,并且每1秒运行一次,所以您可能会减慢其他所有操作的速度。UIButton事件位于主线程上,因此很可能因为您在主线程上执行所有操作,所以它被阻塞

对于不那么准确但不会挂起主线程的计时器实现,请参见以下答案:


如果您必须具有NSTimer实现的一致性,请尝试减少UpdateTime:所做的工作。

我以前遇到过这个问题。您应该使用UIActivityIndicatorView

按钮延迟可能是由UpdateTime方法引起的。在视图中使用UIActivityIndicatorView将显示ViewDidLoad,然后执行UpdateTime方法

我的意思是:

-(void) ViewDidLoad
{
UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    [act setFrame:CGRectMake(320/2-50, 130, 100, 100)];
    act.layer.cornerRadius = 10;
    [act.layer setBackgroundColor:[[UIColor colorWithWhite: 0.0 alpha:0.30] CGColor]];

    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, act.frame.size.width, 20)];
    [lable setText:[NSString stringWithFormat:@"%@", string]];
    [lable setFont:[UIFont fontWithName:@"Helvetica-Light" size:12.0f]];
    [lable setTextAlignment:NSTextAlignmentCenter];
    [lable setTextColor:[UIColor whiteColor]];
    [act addSubview:lable];
    [self.view addSubview: act];
    [act startAnimating];

    // perform the method here, and set your delay time..
    [self performSelector:@selector(UpdateTime:) withObject:nil afterDelay:1.0];

}
然后

- (void)UpdateTime:(id)sender
{
    // Most of your code
}

评论并告诉我这是否有帮助:

在-voidUpdateTime:idsender中你做什么?能否显示在视图控制器之间切换的代码?
-(void) ViewDidLoad
{
UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    [act setFrame:CGRectMake(320/2-50, 130, 100, 100)];
    act.layer.cornerRadius = 10;
    [act.layer setBackgroundColor:[[UIColor colorWithWhite: 0.0 alpha:0.30] CGColor]];

    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, act.frame.size.width, 20)];
    [lable setText:[NSString stringWithFormat:@"%@", string]];
    [lable setFont:[UIFont fontWithName:@"Helvetica-Light" size:12.0f]];
    [lable setTextAlignment:NSTextAlignmentCenter];
    [lable setTextColor:[UIColor whiteColor]];
    [act addSubview:lable];
    [self.view addSubview: act];
    [act startAnimating];

    // perform the method here, and set your delay time..
    [self performSelector:@selector(UpdateTime:) withObject:nil afterDelay:1.0];

}
- (void)UpdateTime:(id)sender
{
    // Most of your code
}