UIA活动指标不会立即显示



由于某种原因,我无法立即显示活动指示器。也许有人能明白为什么?

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);
}

微调器仅在与服务器建立连接时才显示,在此之前它不会显示。有什么想法吗?

使用以下更新的代码。我认为它会起作用。

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);
     } 
}

替换以下代码

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

而不是。。

[旋转器开始动画];

方法后面[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);
   }
});

最新更新