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

时间:2012-01-10 22:15:45

标签: ios xcode web-services uiactivityindicatorview pushviewcontroller

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

- (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];
}

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

2 个答案:

答案 0 :(得分:5)

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

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

[activityIndicator stopAnimating];
[[self navigationController] pushViewController:eventController animated:YES];

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

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

EventController

为了清晰起见,它使用GCD,通常“访问视图属性以强制- (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]; }); }); } / loadView”黑客攻击。

答案 1 :(得分:-3)

您需要为activityIndicator设置帧大小。

activityIndicator.frame = CGRectMake(x, y, 40, 40);