这是对我先前回答的问题的补充问题, 关于在iOS中检测UITextView上属性文本的轻击。
我在Xcode 7.1.1和iOS 9.1上重新测试了以下代码,并且它与我链接的答案描述的设置一起正常工作。
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的答案。
delaysTouchesBegan
设置为YES,以优先处理您的手势。2:子类化TextField并在自定义的touchesBegan方法中处理轻拍事件。 - SolaWing