您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

UIActivityIndicatorView 使用指南:兩種載入提示的做法

編輯:iOS 相關資訊

UIActivityIndicatorView 是 iOS 中用來表示「某項工作正在進行」的標準元件,最常見的用途就是等待資料載入時的轉圈提示。

用法一:單純的轉圈指示器

@property (nonatomic, strong) UIActivityIndicatorView *progressInd;

- (void)showWaiting {
    progressInd = [[UIActivityIndicatorView alloc]
        initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    progressInd.center = CGPointMake(self.view.center.x, 240);
    [self.navigationController.view addSubview:progressInd];
    [progressInd startAnimating];
}

- (void)hideWaiting {
    [progressInd stopAnimating];
}

三種 style 分別是 WhiteLarge、White 與 Gray,請依背景亮度挑選,否則轉圈會看不清。要注意 activityIndicatorView 預設是 hidesWhenStopped = YES,所以 stopAnimating 之後它會自動隱藏,不必另外呼叫 setHidden:。

用法二:半透明背景的載入提示

實務上使用者更需要「有文字說明、且能阻擋背後操作」的提示框。做法是自己包一個半透明容器,把指示器與文字標籤放進去:

- (void)showWaitingInView:(UIView *)parent {
    CGFloat width = 110, height = 70;
    CGRect box = CGRectMake(100, 200, width, height);

    // 1. 指示器置中
    UIActivityIndicatorView *ind =
        [[UIActivityIndicatorView alloc]
            initWithFrame:CGRectMake((width - 32) / 2, (height - 37) / 2, 32, 37)];
    ind.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [ind startAnimating];

    // 2. 說明文字
    UILabel *label = [[UILabel alloc] initWithFrame:
        CGRectMake(0, (height - 37) / 2 + 37, width, 20)];
    label.text = @"Loading...";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];

    // 3. 半透明容器
    UIView *container = [[UIView alloc] initWithFrame:box];
    container.backgroundColor = [UIColor blackColor];
    container.alpha = 0.7;
    container.layer.cornerRadius = 8.0;
    [container addSubview:ind];
    [container addSubview:label];

    container.tag = 9999;
    [parent addSubview:container];
}

- (void)hideWaiting {
    [[self.view viewWithTag:9999] removeFromSuperview];
}

幾個實務建議

1. 避免用 tag 辨識 view。 用 tag 9999 來找容器雖然可行,但容易與其他 view 衝突。更好的做法是宣告一個強參照屬性,直接對它 removeFromSuperview,型別安全且不需魔法數字。

2. 指示器要在主執行緒啟動。 若在背景執行緒呼叫 startAnimating,動畫不會顯示。

3. 記得配對 stop。 建議用 try/finally 思維或 defer 確保任何分支路徑都會隱藏提示,否則使用者會看到永遠轉圈的畫面。

4. 可取消性。 若請求可能耗時很久,考慮改用 UIActivityIndicatorView 加上「取消」按鈕,或改用可互動的 HUD 元件(如 MBProgressHUD、SVProgressHUD),讓使用者能中止操作。

5. 現代替代方案。 iOS 8 之後,非同步載入更推薦用 UIRefreshControl(下拉更新)或 UITableView 的 loadViewIfNeeded 搭配骨架畫面(skeleton view)。骨架畫面被實證能有效降低使用者感知的等待時間,比轉圈圖示友善得多。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved