这是a previous answer of mine对问题Detecting taps on attributed text in a UITextView in 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
设置已更改,以便它既可编辑又可选择
然后这将导致键盘显示。显示键盘后,不再调用tap事件处理程序。在键盘显示时可以做些什么来检测属性文本上的点击?
更新
虽然这里的代码是在Swift中,但最初提出这个问题的人(在我上面链接的答案的评论中)正在使用Objective-C。因此,我很乐意接受Swift或Objective-C中的答案。
答案 0 :(得分:0)
In your UITextView's controller,you can implement UITextViewDelegate
, Then override method
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{
}
Inside this method you can access the textView's selectedRange,which should also be the "tap range" of your attributed text. Then return true / false depending on your needs.