在didSelectRowAtIndexPath中调用pushViewController时无法显示UIActivityIndi​​cator

Hoo*_*adi 0 xcode web-services uiactivityindicatorview pushviewcontroller ios

这是我的代码......

- (void) threadStartAnimating {
    [activityIndicator startAnimating];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    activityIndicator=[[UIActivityIndicatorView alloc] init];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicator.center=[self tableView].center;
    [[self tableView] addSubview:activityIndicator];

    [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
    EventController *eventController = [[EventController alloc] init];
    [eventController setEventID:[[lineItems objectAtIndex:[indexPath row]] objectForKey:@"view_event_button_param"]];
    [activityIndicator stopAnimating];
    [[self navigationController] pushViewController:eventController animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

事件控制器包含一个需要几秒钟才能加载的Web服务.我可以让活动指示器显示的唯一方法是,如果我在那里抛出一个无限循环......我发现了一些例子,提到将它放在一个单独的线程中,但它似乎不起作用.

mat*_*way 5

您的问题是,如果您正在获取数据,viewDidLoad则在加载视图之后才会调用该方法,这通常是在首次显示该视图控制器的过程中.在你的情况下,这是在pushViewController:animated:通话期间.

所以,做你想做的事的一种方法可能是交换这两行:

[activityIndicator stopAnimating];
[[self navigationController] pushViewController:eventController animated:YES];
Run Code Online (Sandbox Code Playgroud)

但是,老实说,我会创建一个名为的协议EventControllerDelegate,id <EventControllerDelegate>在你的内容中有一个弱引用属性EventController,然后设置视图控制器,EventController在你推送它之前创建代理.然后在委托中定义一个方法并在视图控制器中实现它,并在该方法中停止微调器.然后EventController,当您加载完数据后,请调用委托方法.

编辑:如果你真的想在不定义委托的情况下这样做,你可以尝试将代码改为:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    activityIndicator=[[UIActivityIndicatorView alloc] init];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicator.center=[self tableView].center;
    [[self tableView] addSubview:activityIndicator];

    EventController *eventController = [[EventController alloc] init];
    [eventController setEventID:[[lineItems objectAtIndex:[indexPath row]] objectForKey:@"view_event_button_param"]];

    [activityIndicator startAnimating];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIView *v = eventController.view;

        dispatch_async(dispatch_get_main_queue(), ^{
            [activityIndicator stopAnimating];
            [[self navigationController] pushViewController:eventController animated:YES];
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

为了清晰起见,它使用GCD,通常"访问视图属性以强制loadView//viewDidLoad黑客".