2016-11-28 37 views
1

我正在視圖頂部添加活動指示符,並希望在活動指示符處於打開狀態時禁用後臺選擇。同樣出於某種原因,在數據顯示在表格視圖中後,我的活動指示器仍會旋轉約30-45秒(取決於網絡速度)。我爲活動指標創建了一個類別。在活動指示符存在時禁用後臺選擇

活動指示燈類別代碼:

- (UIView *)overlayView { 
    return objc_getAssociatedObject(self, OverlayViewKey); 
} 

- (void)setOverlayView:(UIView *)overlayView { 
    objc_setAssociatedObject(self, OverlayViewKey, overlayView, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
} 

- (void)showActivityIndicatorForView:(UIView *)view { 
    self.overlayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]; 
    self.center = self.overlayView.center; 
    [view setUserInteractionEnabled:NO]; 
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents]; 
    [self.overlayView setUserInteractionEnabled:NO]; 
    [self startAnimating]; 
    [self.overlayView addSubview:self]; 
    [view addSubview:self.overlayView]; 
    [view bringSubviewToFront:self.overlayView]; 
    self.hidesWhenStopped = YES; 
    self.hidden = NO; 

} 

- (void)hideActivityIndicatorForView:(UIView *)view { 
    [self stopAnimating]; 
    [self.overlayView setUserInteractionEnabled:YES]; 
    [self.overlayView removeFromSuperview]; 
    [[UIApplication sharedApplication] endIgnoringInteractionEvents]; 
    [view setUserInteractionEnabled:YES]; 
} 

用法表視圖控制器:

@interface MyTableViewController() 
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator; 
@end 

@implementation MyTableViewController 
- (id) initWithSomething:(NSString *)something { 
    self = [super init]; 

    if (self) { 
     self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; 
     self.activityIndicator.overlayView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]; 
    } 
    return self; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [self getDataServiceRequest]; 
    [self.activityIndicator showActivityIndicatorForView:self.navigationController.view]; 
} 

- (void)requestCompletionCallBack sender:(ServiceAPI *)sender { 
// Do something here with the data 
    [self.activityIndicator hideActivityIndicatorForView:self.navigationController.view]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self.tableView reloadData]; 
    }); 
} 
@end 

我在做什麼錯在這裏?爲什麼我仍然能夠在活動指示器打開時以及即使在禁用用戶交互之後在後臺選擇數據。

回答

0

將您的調用移動到hideActivityIndi​​catorForView到dispatch_async(dispatch_get_main_queue()的調用中。這是一個UI調用,需要在主線程中完成。至於如何在您的視圖控制器上禁用其他操作,您有幾個選項。我所做的一件簡單的事情就是將活動指示器放置在固定在整個屏幕上的視圖中,將其設置爲opaque = false,並將顏色設置爲黑色,並將alpha設置爲0.5。這種方式下面的內容是可見的,但用戶無法點擊它。您需要爲「覆蓋視圖」添加一個插座並顯示 - 隱藏它,而不是顯示/隱藏活動指示器視圖。

+0

移動內部dispatch_async hideActivityIndi​​catorForView呼叫幫助了我。現在我的活動指示消失了,不久之後,我在屏幕上看到數據。有了這個,我沒有看到一個場景,當數據在屏幕上時,活動指示器仍在旋轉。我想我應該可以跳過添加一個不透明的覆蓋視圖。謝謝@Duncan C! –

0

dispatch_async(dispatch_get_main_queue(), ^{ [self.tableView reloadData]; }); 修復它 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];