Это дополнительный вопрос к предыдущему моему вопросу на вопрос Обнаружение ответвлений от атрибута текста в UITextView в IOS.
Я повторил следующий код с 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.