我正在尝试创建一个笔记记录应用,您可以在其中单击图像以及正常编辑文本。
当前,我已经在调用的UITextView上放置了一个轻击手势识别器:
@IBAction func onImageTap(_ sender: UITapGestureRecognizer) {
if sender.state == .ended {
let textView = sender.view as! UITextView
let layoutManager = textView.layoutManager
// location of tap in textView coordinates
var location = sender.location(in: textView)
location.x -= textView.textContainerInset.left;
location.y -= textView.textContainerInset.top;
// character index at tap location
let characterIndex = layoutManager.characterIndex(for: location, in: textView.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
// if index is valid
if characterIndex < textView.textStorage.length {
// check if the tap location has the image attribute
let attributeValue = textView.attributedText.attribute(NSAttributedString.Key.fileType, at: characterIndex, effectiveRange: nil) as? String
// if location does have custom attribute, extract the url of the PDF and perform segue to display PDF
if let value = attributeValue {
if value == "PDF" {
storedFileName = textView.attributedText.attribute(NSAttributedString.Key.fileName, at: characterIndex, effectiveRange: nil) as? String
performSegue(withIdentifier: "displayPDF", sender: textView)
}
} else {
textView.isEditable = true
textView.becomeFirstResponder()
}
}
}
}
这会使所有图像都可点击。但是,然后我无法再单击UITextView中的任何其他位置来编辑文本。
我该怎么做,以使图像保持可单击状态,但是,如果我单击UITextView中的其他位置,则可以开始编辑文本了?
假设您已将图像作为UITextView
添加到NSAttachment
,从iOS 9.0开始,您可以检查给定的NSRange
是否包含附件:
let characterIndex = 25
let range = NSRange(location: characterIndex, length: 1)
// Using an IBOutlet in the current view controller called 'textView'
if textView.attributedText.containsAttachments(in: range) {
// Do some activity
}