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

iOS 視圖添加觸摸事件:疊加透明 UIButton 並設定 TouchUpInside 目標

     編輯:程式設計綜合問答

在任意視圖上添加觸摸響應,最簡單方式是加入一個透明 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 {
    // 處理觸摸邏輯
}

優點

  • 自動處理觸摸狀態(高亮、追蹤)。
  • 支援無障礙、VoiceOver。
  • 可透過 isEnabled 控制啟用/禁用。

替代方案

  • UITapGestureRecognizer:
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [self.view addGestureRecognizer:tap];
  • 覆寫 touchesBegan/Moved/Ended(需啟用 userInteractionEnabled)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved