MBProgressHUD 幾乎是每個 iOS 專案都會用到的 loading 與提示元件。以下把導入步驟與常用寫法整理成可直接複用的片段。
1、下載 MBProgressHUD 原始碼包加入工程(實際上只有一個 .h 與一個 .m)。
2、進入 Build Phases,把原始碼包中的 .m 檔加入編譯。
3、加入主標頭檔 MBProgressHUD.h。
// 一進入就顯示提示條 MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:webView animated:YES]; // 加上一層遮罩,讓背景不可操作 hud.dimBackground = YES; hud.labelText = @"頁面加載中..."; // 載入完成後隱藏 [MBProgressHUD hideAllHUDsForView:webView animated:YES];
封裝成類別方法,方便專案各處呼叫:
+ (void)showMsg:(NSString *)msg imgName:(NSString *)imgName {
// 顯示到主視窗
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
// 顯示模式改為自訂圖片;mode 必須在 customView 赋值之前設定
hud.mode = MBProgressHUDModeCustomView;
int delay = 1;
if ([imgName isEqualToString:@"error.png"]) {
// 錯誤提示停留久一點,讓使用者看得清楚
delay = 3;
}
imgName = [NSString stringWithFormat:@"MBProgressHUD.bundle/%@", imgName];
hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgName]];
hud.labelText = msg;
// 必須為 YES,隱藏時才會從父視圖中移除
hud.removeFromSuperViewOnHide = YES;
[hud hide:YES afterDelay:delay];
}
// 提示框背景色 hud.color = [UIColor clearColor]; // 這裡表示不要背景 // 下方的小字說明 hud.detailsLabelText = @"detail"; // 陰影遮罩效果 hud.dimBackground = YES; // 1 秒後隱藏 [hud hide:YES afterDelay:1]; // 只顯示文字 hud.mode = MBProgressHUDModeText; // 外邊距與 Y 軸偏移 hud.margin = 0; hud.yOffset = 0; // 隱藏後從父視圖移除 hud.removeFromSuperViewOnHide = YES; // 圓形進度條 hud.mode = MBProgressHUDModeAnnularDeterminate;
實務上要特別注意 removeFromSuperViewOnHide 這個屬性。若不設為 YES,HUD 雖然不可見,節點仍留在視圖層級中,長時間運行下容易累積出意料之外的 hitTest 問題。另外若在非主線程發出請求,記得把 show 與 hide 都切回主線程再呼叫。