UIActivityIndi​​cator没有立即显示

时间:2012-11-30 06:47:36

标签: objective-c ios cocoa-touch

由于某些原因,我无法立即显示活动指示。也许有人能看出原因?

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = self.view.center; 
_active = spinner;
[self.view addSubview:spinner];
[spinner startAnimating];
@try {

    [self connectToServerUsingStream:ip portNo:port];
    NSString *text = @"test";
    const uint8_t *str =
    (uint8_t *) [text cStringUsingEncoding:NSASCIIStringEncoding];
    [self writeToServer:str];

}
@catch (NSException * e) {
    NSLog(@"Exception: %@", e);
}

微调器只显示然后连接到服务器,之前它没有显示。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

使用以下更新的代码。我认为它会奏效。

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = self.view.center; 
 _active = spinner; 
[self.view addSubview:spinner]; 
[spinner startAnimating]; 
[self performSelector:@selector(performTask) withObject:nil afterDelay:0.0];

- (void)performTask {
     @try {
         [self connectToServerUsingStream:ip portNo:port];
         NSString *text = @"test";
         const uint8_t *str =
         (uint8_t *) [text cStringUsingEncoding:NSASCIIStringEncoding];
         [self writeToServer:str];

     }
     @catch (NSException * e) {
         NSLog(@"Exception: %@", e);
     } 
}

答案 1 :(得分:0)

替换以下代码

[spinner performSelectorOnMainThread:@selector(startAnimating) withObject:nil waitUntilDone:TRUE];

而不是..

[spinner startAnimating];

答案 2 :(得分:0)

[spinner startAnimating];方法之后的这一行阻止主线程,这就是活动未显示的原因。

请更改以下代码:

dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(taskQ, ^{
   @try
   {

     [self connectToServerUsingStream:ip portNo:port];
     NSString *text = @"test";
     const uint8_t *str =
     (uint8_t *) [text cStringUsingEncoding:NSASCIIStringEncoding];
     [self writeToServer:str];
   }
   @catch (NSException * e)
   {
     NSLog(@"Exception: %@", e);
   }
});