首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS Cocos2D 禁用觸摸交互:下載期間防止用戶操作

     編輯:程式設計綜合問答

需求場景

文件下載、網絡請求等異步操作期間,需完全禁用用戶觸摸交互,防止重複觸發或干擾進行中任務。

核心 API

// 禁用所有觸摸事件
[[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(@"下載完成,用戶可操作");
}];

注意事項

  • 計數器模式:多並發請求時需引用計數,避免提前恢復交互
  • 超時保護:添加定時器強制恢復,防止請求卡死導致應用無響應
  • 視覺反饋:建議配合載入指示器(UIActivityIndicatorView)提示用戶等待
  • iOS 13+:beginIgnoringInteractionEvents 已棄用,推薦使用 view.isUserInteractionEnabled = NO 針對性禁用特定視圖

現代替代方案

// 禁用特定視圖層級交互(推薦)
self.view.isUserInteractionEnabled = NO;
// 彈出載入視圖
[self.view addSubview:loadingView];

// 完成後恢復
self.view.isUserInteractionEnabled = YES;
[loadingView removeFromSuperview];

總結

beginIgnoringInteractionEvents 是全局禁用觸摸的簡便方法,但現代開發傾向於視圖級控制,配合載入狀態 UI 體驗更佳。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved