2014-03-27 47 views
0

我有一个视图控制器,它继承了第二个视图控制器,该视图控制器加载了多个图像,但在从第一个VC到第二个图像之前,它会挂起一两秒钟。我试图添加一个UIActivityIndi​​catorView,以便用户不认为该应用程序被冻结(这是目前的感觉)。然而,我似乎无法让它正常工作,并且我看到的所有示例都使用Web视图或正从服务器访问某种数据,而我正在加载存储在应用程序中的图像。在切换视图控制器时显示UIActivityIndi​​catorView

我下面有一些代码来显示我所尝试的。

.h文件中

@interface SecondViewController: UIViewController 
@property (strong, nonatomic) UIActivityIndicatorView *indicator; 

.m文件

-(void)viewWillAppear:(BOOL)animated 
{ 
    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 

    self.indicator.center = CGPointMake(160, 240); 

    [self.view addSubview:self.indicator]; 

    //Loading a lot of images in a for loop. 
    //The images are attached to buttons which the user can press to bring up 
    //an exploded view in a different controller with additional information 
    [self.indicator startAnimating]; 
    for{....} 
    [self.indicator stopAnimating]; 
} 

我曾尝试使用也将dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)呼吁[self.indicator startAnimating],但所发生的一切是视图控制器即刻加载和图片后,立即/按钮从不加载。

当用户单击第一个视图控制器上的“下一个”按钮时,如何摆脱延迟?应用程序挂在第一个VC大约一两秒钟,然后最后加载第二个视图控制器与所有的图像/按钮。我是否需要将UIActivityIndicatorView添加到第一个视图控制器,或者我是否完全错误地进行了这种操作?我愿意接受任何和所有的方法来完成这件事,事先要感谢。

回答

1

您需要在下一个运行循环中调用初始化代码和stopAnimating。一个简单的事情你可以做的是:

-(void)viewWillAppear:(BOOL)animated 
{ 
    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; 
    self.indicator.center = CGPointMake(160, 240); 

    [self.view addSubview:self.indicator]; 

    //Loading a lot of images in a for loop. 
    //The images are attached to buttons which the user can press to bring up 
    //an exploded view in a different controller with additional information 
    [self.indicator startAnimating]; 
    [self performSelector:@selector(loadUI) withObject:nil afterDelay:0.01]; 
} 

-(void) loadUI { 
    for{....} 
    [self.indicator stopAnimating]; 
} 

当然也有其他的方式来在未来的运行循环运行loadUI(如使用定时器)。

+1

这种方式将挂起主线程,而用户界面将是不负责任的。您应该在后台线程中加载UI并派发到主线程来更新UI。 – sahara108

+0

用户界面将被阻止,直到“for {...}”部分完成,但活动指示器将正确地进行动画。实现实际上取决于设计:您是否希望用户能够在“for {...}”初始化完成之前与UI进行交互。如果在后台线程中调用loadUI并分派给主线程,则用户将能够在“for {...}”完成之前与UI进行交互,这可能不是作者想要的。 – subchap

+0

在图像/按钮加载之前,用户不需要与应用程序进行任何交互。我希望应用程序显示指示器,直到图像全部加载。 – DevilsDime

相关问题