在UITextView中拖放时显示文本光标

时间:2017-11-17 11:25:23

标签: ios swift drag-and-drop uitextview

我正在我的应用中实施拖放。

将应用拖放的主要屏幕之一(主要是掉落)位于UITextView

我已使用以下代码向此UITextView添加了放置互动:

    let dropInteraction = UIDropInteraction(delegate: self)     
    inputTextView.addInteraction(dropInteraction)

通过这样做,我现在接受它的下降。

为了只接受图像和文本作为drop我已经实现了以下委托方法:

func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
    return session.hasItemsConforming(toTypeIdentifiers: [kUTTypeImage as String, kUTTypeText as String]) && session.items.count == 1
}

根据需要,我已经实现了以下必需的委托方法来返回UIDropProposal

func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
    let dropProposal: UIDropProposal = UIDropProposal(operation: .copy)
    dropProposal.isPrecise = true
    return dropProposal
}

然后在performDrop委托方法中我处理删除的内容并将其附加到UITextView

func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
    // Access the dropped object types: UIImage, NSString
    session.loadObjects(ofClass: UIImage.self) { (imageItems) in

        let images = imageItems as! [UIImage]
        guard var image = images.first else { return }
        // scale the image 
        image = UIImage(cgImage: image.cgImage!, scale: 4, orientation: .up)

        let currentText: NSMutableAttributedString = NSMutableAttributedString(attributedString: self.inputTextView.attributedText)
        let textAttachment = NSTextAttachment()
        textAttachment.image = image
        let imageText = NSAttributedString(attachment: textAttachment).mutableCopy() as! NSMutableAttributedString
        let imageStyle = NSMutableParagraphStyle()
        imageStyle.alignment = .center

        imageText.addAttribute(NSAttributedStringKey.paragraphStyle, value: imageStyle, range: NSMakeRange(0, imageText.length))

        // Prepares the string to append with line breaks and the image centered
        let attributedStringToAppend: NSMutableAttributedString = NSMutableAttributedString(attributedString: NSAttributedString(string: "\n\n"))
        attributedStringToAppend.append(imageText)
        attributedStringToAppend.append(NSAttributedString(string: "\n\n"))

        // Applies text attributes to the NSMutableAttrString as the default text input attributes
        let range: NSRange = NSRange.init(location: 0, length: attributedStringToAppend.length)
        let style = NSMutableParagraphStyle()
        style.lineSpacing = 4
        style.alignment = .center
        let font = Font(.installed(.OpenSansRegular), size: .custom(18)).instance
        let attr: [NSAttributedStringKey : Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.paragraphStyle.rawValue): style, NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue): font, NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): UIColor.rgb(red: 52, green: 52, blue: 52)]

        attributedStringToAppend.addAttributes(attr, range: range)

        let location = self.inputTextView.selectedRange.location

        currentText.insert(attributedStringToAppend, at: location)

        self.inputTextView.attributedText = currentText                     
    }

    session.loadObjects(ofClass: NSString.self) { (stringItems) in
        let strings = stringItems as! [NSString]
        guard let text = strings.first else { return }
        self.inputTextView.insertText(text as String)
    }                   
}

通过完成所有这些操作,图像和文本都会按预期方式删除到所需的字段中,但我在这里遇到一个问题。

在邮件应用中的New Mail Composer中,当您将项目或图片拖到其中时,它会显示跟踪光标,以便您知道丢弃内容的去向,但我不能在我的示例中执行此操作

drop落到现有文本的末尾。

如果我想要放到一个特定的位置,我必须先将光标放在所需的位置,然后执行放置,所以在你看到的performDrop函数中,我检索光标位置selectedRange

我想看到光标流正在发生投放动画,就像邮件应用程序或笔记应用程序一样,您可以在其中选择放置对象的位置。

有没有人提示如何实现这个目标?

提前致谢。

2 个答案:

答案 0 :(得分:2)

您可以将selectedRange设置为NSRange,并使用有效位置和0长度,在textView或textField中移动光标。

我不会用完成的代码破坏你,而是逐步解释如何自己解决问题:

  1. 在超级视图中计算触摸的当前位置,例如,您可以使用touchesMoved:,然后将触摸的位置转换为textView的坐标系

  2. 通过应用textView的文本属性(字体,大小等)来计算textView的text的边界矩形,如下所示:

    [textView.text boundingRectWithSize:textView.bounds.size options:NSStringDrawingUsesLineFragmentOrigin attributes:textAttributesDict context:nil]

  3. 将触摸位置与文字的边界矩形相匹配,并在文字中找到所需的位置

  4. textView.selectedRange设为NSMakeRange(calculatedLoc, 0)

答案 1 :(得分:0)

我发现最简单的方法是更新 sessionDidUpdate 中的光标。

func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
    inputTextView.becomeFirstResponder()
    let point = session.location(in: textView)
    if let position = inputTextView.closestPosition(to: point) {
        inputTextView.selectedTextRange = inputTextView.textRange(from: position, to: position)
    }
    
    let dropProposal: UIDropProposal = UIDropProposal(operation: .copy)
    dropProposal.isPrecise = true
    return dropProposal
}