iOS - 如何在活动视图仍在动画时显示UIView?

时间:2012-09-21 12:00:24

标签: ios animation uiview

当我的应用加载某些屏幕时,我有代码显示带有活动轮的“正在加载...”视图。如果加载需要特别长的时间(例如,超过4秒),那么我想显示一条额外的消息,上面写着“对不起,这需要很长时间,请耐心等待!”我这样做的方法是在4秒延迟时使用NSTimer调用方法来创建等待视图,然后在加载视图上覆盖这个新视图,使得单词不重叠。如果页面加载时间不到4秒,则加载视图将被隐藏,等待视图永远不会被触发,用户可以快乐地进行加载。

当我测试超过4秒的屏幕加载时,我似乎无法显示其他视图。这是我的代码:

// this method is triggered elsewhere in my code
// right before the code to start loading a screen
- (void)showActivityViewer
{     
    tooLong = YES;
    waitTimer = [NSTimer scheduledTimerWithTimeInterval:4.0
                                                   target:self
                                                 selector:@selector(createWaitAlert)
                                                 userInfo:nil
                                                  repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer: waitTimer forMode: NSDefaultRunLoopMode];

    loadingView = [LoadingView createLoadingView:self.view.bounds.size.width     :self.view.bounds.size.height];    
    [self.view addSubview: loadingView];

    // this next line animates the activity wheel which is a subview of loadingView
    [[[loadingView subviews] objectAtIndex:0] startAnimating]; 
}

- (void)createWaitAlert
{
    [waitTimer invalidate];
    if (tooLong) 
    {
        UIView *waitView = [LoadingView createWaitView:self.view.bounds.size.width :self.view.bounds.size.height];
        [self.view addSubview:waitView];
    }
}

// this method gets triggered elsewhere in my code
// when the screen has finished loading and is ready to display
- (void)hideActivityViewer
{
    tooLong = NO;
    [[[loadingView subviews] objectAtIndex:0] stopAnimating];
    [loadingView removeFromSuperview];
    loadingView = nil;
}

1 个答案:

答案 0 :(得分:0)

您确定要从主线程执行此操作吗?试试这个:

- (void)showActivityViewer
{     
    tooLong = YES;

    dispatch_async(dispatch_queue_create(@"myQueue", NULL), ^{
        [NSThread sleepForTimeInterval:4];
        [self createWaitAlert];
    });

    loadingView = [LoadingView createLoadingView:self.view.bounds.size.width     :self.view.bounds.size.height];    
    [self.view addSubview: loadingView];

    // this next line animates the activity wheel which is a subview of loadingView
    [[[loadingView subviews] objectAtIndex:0] startAnimating]; 
}

- (void)createWaitAlert
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (tooLong) 
        {
            UIView *waitView = [LoadingView createWaitView:self.view.bounds.size.width :self.view.bounds.size.height];
            [self.view addSubview:waitView];
        }
    });
}