How to enable drag and drop in UITextfield in iOS 11

I know it's too early to ask about the development of the latest iOS 11 Drag and Drop feature . It also says All drag and drop functionality is available on iPad. On iPhone, drag and drop is only available in the app.

So I am looking to move a textbox in one app on an iPhone. I looked at the class UIDragInteraction

, but I don't know how to enable or activate the drag- UITextfield

and -drop feature in , and I also noticed that the property is .textDragDelegate

added to UITextfield

, but I don’t know how to actively drag and drop.

Look for suggestions or help who have already practiced this.

thank

+3


source to share


1 answer


For iPhone, if DnD is for the same screen, it's tricky:

  • Touch detection on UITextField
  • Make a "visual copy" of this text box if the user still touches the screen and moves their finger.
  • Move this "visual copy" as your finger moves.
  • When the user releases their finger, determine the position to place this "visual copy"
  • Make a copy of the uitextfield object, call addSubview to add at the desired position.
  • Adjust the autodetect limit of this new uitext field
  • Remove the old uitextfield + adjust the auto-detection of the view associated with it.

For DnD between screens, it is technically possible, but the application must be designed for this requirement.

To enable drag and drop UIView object for iPad you need to create dragInteraction and add it to your UIViewObject. Then you will also need to include dropInteraction in your ViewController.

For example (not tested):

@IBOutlet weak var dragableTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    //enable drag for your 'dragableTextField'
    let dragInteraction = UIDragInteraction(delegate: self)
    self.dragableTextField.addInteraction(dragInteraction)

    //set up drop interaction delegate to this ViewController.
    let dropInteraction = UIDropInteraction(delegate: self)
    self.view.addInteraction(dropInteraction)
}

      



and implement delegates

extension ViewController : UIDragInteractionDelegate {
    //this is mandatory
    func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
        //implement your code

    }
}

extension ViewController : UIDropInteractionDelegate {
    //this is optional
    func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
        // If you want to enable drag-drop on UITextField object only:
        return session.canLoadObjects(ofClass: [UITextField.self])
    }
}

      

You need more work loading data or updating the UI on the target. You can find out more:

https://developer.apple.com/documentation/uikit/drag_and_drop/making_a_view_into_a_drop_destination

and https://developer.apple.com/documentation/uikit/drag_and_drop/adopting_drag_and_drop_in_a_custom_view

+2


source







All Articles