在任意視圖上添加觸摸響應,最簡單方式是加入一個透明 UIButton 覆蓋整個視圖,設定 TouchUpInside 目標動作。
UIButton *transparentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
transparentBtn.frame = self.view.bounds;
transparentBtn.backgroundColor = [UIColor clearColor];
[transparentBtn addTarget:self action:@selector(handleTap:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:transparentBtn];
- (void)handleTap:(UIButton *)sender {
// 處理觸摸邏輯
}
isEnabled 控制啟用/禁用。UITapGestureRecognizer:UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [self.view addGestureRecognizer:tap];touchesBegan/Moved/Ended(需啟用 userInteractionEnabled)。