在显示键盘时检测UITextView中属性文本的轻敲

这是对我以前的答案的补充问题检测在UITextView在iOS中的属性文本的轻拍 。

我使用Xcode 7.1.1和iOS 9.1重新testing了下面的代码,并且它与链接到的答案中描述的设置正常工作。

import UIKit class ViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() // Create an attributed string let myString = NSMutableAttributedString(string: "Swift attributed text") // Set an attribute on part of the string let myRange = NSRange(location: 0, length: 5) // range of "Swift" let myCustomAttribute = [ "MyCustomAttributeName": "some value"] myString.addAttributes(myCustomAttribute, range: myRange) textView.attributedText = myString // Add tap gesture recognizer to Text View let tap = UITapGestureRecognizer(target: self, action: Selector("myMethodToHandleTap:")) tap.delegate = self textView.addGestureRecognizer(tap) } func myMethodToHandleTap(sender: UITapGestureRecognizer) { let myTextView = sender.view as! UITextView let layoutManager = myTextView.layoutManager // location of tap in myTextView coordinates and taking the inset into account var location = sender.locationInView(myTextView) location.x -= myTextView.textContainerInset.left; location.y -= myTextView.textContainerInset.top; // character index at tap location let characterIndex = layoutManager.characterIndexForPoint(location, inTextContainer: myTextView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil) // if index is valid then do something. if characterIndex < myTextView.textStorage.length { // print the character index print("character index: \(characterIndex)") // print the character at the index let myRange = NSRange(location: characterIndex, length: 1) let substring = (myTextView.attributedText.string as NSString).substringWithRange(myRange) print("character at index: \(substring)") // check if the tap location has a certain attribute let attributeName = "MyCustomAttributeName" let attributeValue = myTextView.attributedText.attribute(attributeName, atIndex: characterIndex, effectiveRange: nil) as? String if let value = attributeValue { print("You tapped on \(attributeName) and the value is: \(value)") } } } } 

但是,如果UITextView设置被更改,以便它是可编辑和可选的

在这里输入图像说明

那么这将导致键盘显示。 显示键盘后,轻敲事件处理程序不再被调用。 在键盘显示时,可以做些什么来检测属性文本的轻敲?

更新

虽然这里的代码是在Swift中,但最初提出这个问题的人(在上面链接到的答案的评论中)正在使用Objective-C。 所以我很乐意接受Swift或Objective-C的答案。

在你的UITextView控制器中,你可以实现UITextViewDelegate ,然后覆盖方法

 -(BOOL)textViewShouldBeginEditing:(UITextView *)textView{ } 

在这个方法里面,你可以访问textView的selectedRange,它也应该是属性文本的“tap range”。 然后根据您的需要返回true / false。