【问题标题】:How to enable Dragging in UITextfield in iOS 11如何在 iOS 11 的 UITextfield 中启用拖动
【发布时间】:2017-11-08 13:42:49
【问题描述】:

我知道现在询问 iOS 11 最新功能的开发还为时过早Drag and Drop。这也说明 所有拖放功能都可以在 iPad 上使用。在 iPhone 上,拖放仅在应用内可用。

所以我希望在 iPhone 的单个应用程序中移动文本字段。我查看了UIDragInteraction 类,但我不知道如何在UITextfield 中启用或主动拖动功能,我还注意到.textDragDelegate 属性添加到UITextfield 但我不知道如何主动拖动。

寻求已经实践过的建议或帮助。

谢谢

【问题讨论】:

    标签: ios iphone xcode drag-and-drop drag


    【解决方案1】:

    对于 iPhone,如果 DnD 是针对同一个屏幕的,那就很棘手了:

    • 检测 UITextField 上的触摸
    • 如果用户仍然触摸屏幕并移动手指,则创建此文本字段的“可视副本”。
    • 当手指移动时移动这个“视觉副本”
    • 当用户松开手指时,检测放置此“视觉副本”的位置
    • 创建uitextfield对象的副本,调用addSubview添加到正确的位置
    • 调整这个新的 uitextfield 的自动布局约束
    • 删除旧的 uitextfield + 调整与之相关的视图的自动布局。

    对于屏幕之间的 DnD,从技术上讲,这是可能的,但应用程序必须针对该要求进行设计。

    要在 iPad 的 UIView 对象上启用拖动,您必须创建一个 dragInteraction 并将其添加到您的 UIViewObject。然后,您还必须为您的 ViewController 启用 dropInteraction。

    例如(未测试):

    @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)
    }
    

    并实现这些委托

    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])
        }
    }
    

    您需要更多的工作来加载数据或更新目标目标的 UI。你可以阅读更多:

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

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

    【讨论】:

    • 我认为您的答案更多地与 iPad 相关,iPad 在应用程序之间拖放,但我希望在同一个应用程序中进行 DnD。
    • 嗯,好的。我想念这个问题。我会更新我的答案。你的意思是在屏幕之间拖动吗?还是只在您应用的同一屏幕中进行 DnD?
    猜你喜欢
    • 2018-05-14
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    相关资源
    最近更新 更多