文件下載、網絡請求等異步操作期間,需完全禁用用戶觸摸交互,防止重複觸發或干擾進行中任務。
// 禁用所有觸摸事件
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
// 恢復觸摸事件
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
@interface NetworkManager : NSObject
+ (instancetype)sharedManager;
- (void)startRequestWithBlock:(void(^)(BOOL success))completion;
@end
@implementation NetworkManager {
NSInteger _requestCount;
}
+ (instancetype)sharedManager {
static NetworkManager *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; });
return instance;
}
- (void)startRequestWithBlock:(void(^)(BOOL))completion {
_requestCount++;
if (_requestCount == 1) {
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
}
// 模擬網絡請求
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
_requestCount--;
if (_requestCount == 0) {
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}
completion(YES);
});
}
@end
[[NetworkManager sharedManager] startRequestWithBlock:^(BOOL success) {
// 請求完成,觸摸已自動恢復
NSLog(@"下載完成,用戶可操作");
}];
beginIgnoringInteractionEvents 已棄用,推薦使用 view.isUserInteractionEnabled = NO 針對性禁用特定視圖// 禁用特定視圖層級交互(推薦)
self.view.isUserInteractionEnabled = NO;
// 彈出載入視圖
[self.view addSubview:loadingView];
// 完成後恢復
self.view.isUserInteractionEnabled = YES;
[loadingView removeFromSuperview];
beginIgnoringInteractionEvents 是全局禁用觸摸的簡便方法,但現代開發傾向於視圖級控制,配合載入狀態 UI 體驗更佳。