首页 > 解决方案 > Swift:拖放委托 - 拖放到另一个文本视图时无法拖出文本视图

问题描述

我目前正在创建一个令人惊叹的比赛类型的移动应用程序,玩家将根据他们的位置玩不同的游戏。他们必须玩的游戏之一是典型的拖放游戏。我目前能够对 2 个文本视图执行拖放操作。然而:

我创建了一个示例来测试它,有 2 个 UITextView - 1 个用于拖放,1 个用于拖放。拖动有效,但我不太确定在将其放入后如何将其拖出。

使用以下视图控制器:

class ViewController: UIViewController, UIDragInteractionDelegate, UIDropInteractionDelegate{
  @IBOutlet weak var dragTextView: UITextView!
  @IBOutlet weak var dropTextView: UITextView!

  override func viewDidLoad() {
    super.viewDidLoad()

    dragTextView.isUserInteractionEnabled = true
    dropTextView.isUserInteractionEnabled = true

    dropTextView.layer.borderWidth = 1
    dropTextView.layer.borderColor = UIColor.lightGray.cgColor

    let dragTextInteraction = UIDragInteraction(delegate: self)
    let dropTextInteraction = UIDropInteraction(delegate: self)

    dragTextInteraction.isEnabled = true

    dragTextView.addInteraction(dragTextInteraction)
    dropTextView.addInteraction(dropTextInteraction)

  }

  func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
    return session.hasItemsConforming(toTypeIdentifiers: [kUTTypePlainText as String])
  }

  func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
    let location = session.location(in: self.view)
    let dropOperation: UIDropOperation?

    if session.canLoadObjects(ofClass: String.self) {

      if dropTextView.frame.contains(location) {
        dropOperation = .copy
      } else {
        dropOperation = .cancel
      }
    } else {
      dropOperation = .cancel
    }

    return UIDropProposal(operation: dropOperation!)
  }

  func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
    if session.canLoadObjects(ofClass: String.self) {

      session.loadObjects(ofClass: String.self) { (items) in
        let values = items as [String]
        self.dropTextView.text = values.last

      }
    }
  }

  func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {

    if let textView = interaction.view as? UITextView {
      let textToDrag = textView.text
      let provider = NSItemProvider(object: textToDrag! as NSString)
      let item = UIDragItem(itemProvider: provider)
      return [item]
    }

    return []
  }
}

一直为此烦恼。任何帮助将不胜感激 :)

标签: iosswiftdrag-and-drop

解决方案


推荐阅读