将UITapGestureRecognizer添加到UITextView而不阻止textView触摸

时间:2015-03-04 15:54:37

标签: ios swift uitextview uitapgesturerecognizer

如何将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行为?

3 个答案:

答案 0 :(得分:21)

要做到这一点,你的视图控制器采用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
}

答案 1 :(得分:3)

如果有人来到这里寻找@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:别忘了< UIGestureRecognizerDelegate>

答案 2 :(得分:0)

Swift 4.2
以下步骤使我可以轻按一下以转出全屏UITextView,同时允许滚动UITextView的内容:

  1. 从UITableView断开UIGestureRecognizer的连接。
  2. 制作CustomTextView:UITextView。
  3. 使用CustomTextView将“发送者”变量添加到特定的UIViewController。
  4. 诱捕“触摸结束...”
  5. 在发送方UIViewController中调用exape函数。

class CustomTextView: UITextView {
    var sender: DocViewController?

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

我可以滚动UITextView的内容,也可以只单击以退出。
在创建时通过托管UIViewController设置了“发送方”。