【问题标题】:Add UITapGestureRecognizer to UITextView without blocking textView touches将 UITapGestureRecognizer 添加到 UITextView 而不阻止 textView 触摸
【发布时间】:2015-05-05 16:53:59
【问题描述】:

我怎样才能将UITapGestureRecognizer 添加到 UITextView 但仍然让UITextView 的触摸正常

目前,只要我向我的 textView 添加自定义手势,它就会阻止点击 UITextView 默认操作,例如定位光标。

var tapTerm:UITapGestureRecognizer = UITapGestureRecognizer()

override func viewDidLoad() {
    tapTerm = UITapGestureRecognizer(target: self, action: "tapTextView:")
    textView.addGestureRecognizer(tapTerm)
}

func tapTextView(sender:UITapGestureRecognizer) {
    println("tapped term – but blocking the tap for textView :-/")
…
}

如何在处理点击的同时保持光标定位等任何 textView 行为不变?

【问题讨论】:

  • 您是否尝试将cancelsTouchesInView 设置为false
  • 当你想移动光标时你会怎么做?

标签: ios swift uitextview uitapgesturerecognizer


【解决方案1】:

Swift 4.2
以下步骤允许我通过点击转义全屏 UITextView,同时允许滚动 UITextView 的内容:

  1. 从 UITableView 断开 UIGestureRecognizer。
  2. 制作了一个CustomTextView:UITextView。
  3. 为带有 CustomTextView 的特定 UIViewController 添加了一个“发送者”变量。
  4. “Touches Ended...”的陷阱
  5. 在发送方 UIViewController 中调用 excape 函数。

class CustomTextView: UITextView {
    var sender: DocViewController?

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let controller = sender {
            controller.handleSwipeGesture()
        }
    }
}

我可以滚动 UITextView 的内容,也可以点击退出。
'sender' 是在创建时从宿主 UIViewController 设置的。

【讨论】:

    【解决方案2】:

    如果有人来这里寻找 @Zell B. 在 Objective C 中的答案,代码如下:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textViewTapped:)];
        tap.delegate = self; 
        tap.numberOfTapsRequired = 1; 
       [self.textView addGestureRecognizer:tap];
    }   
    
    - (void)textViewTapped:(UITapGestureRecognizer *)tap {
        //DO SOMTHING 
    }
    
    #pragma mark - Gesture recognizer delegate
    
    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
        return YES; 
    }
    

    PS:别忘了

    【讨论】:

      【解决方案3】:

      要做到这一点,让您的视图控制器采用 UIGestureRecognizerDelegate 并覆盖应该与手势识别器方法同时识别,例如:

      override func viewDidLoad() {
          tapTerm = UITapGestureRecognizer(target: self, action: "tapTextView:")
          tapTerm.delegate = self
          textView.addGestureRecognizer(tapTerm)
      }
      
      func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
      
          return true
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多