簡體   English   中英

如何讓iOS 11拖放工作在iPhone上

[英]How to get iOS 11 drag and drop working on the iPhone

我一直在嘗試新的iOS 11拖放功能。 這很棒,但它只適用於iPad。 蘋果聲稱它也適用於iPhone,但我無法在那里工作? Apple的說法是假的,還是我做錯了什么?

你正在某個視圖上安裝UIDragInteraction對象,對嗎? 嗯,默認情況下,iPhone上的拖拽交互的isEnabled屬性為false (根據isEnabledByDefault類屬性的設備相關值)。

因此,要在iPhone上打開拖放功能,只需在創建時將拖動交互的isEnabled為true:

override func viewDidLoad() {
    super.viewDidLoad()

    let dragger = UIDragInteraction(delegate: self)
    self.dragView.addInteraction(dragger)
    dragger.isEnabled = true // for iPhone: presto, we've got drag and drop!
}

類似地,對於表視圖或集合視圖,如另一個答案所指出的,您需要將其dragInteractionEnabled設置為true ,因為它在iPhone上默認為false

使用Swift 4和iOS 11,根據您的需要,您可以選擇以下方法之一來解決您的問題。


#1。 允許在iPhone上為UITableView拖放交互

UITableView有一個名為dragInteractionEnabled的屬性。 dragInteractionEnabled具有以下聲明

var dragInteractionEnabled: Bool { get set }

一個布爾值,指示表視圖是否支持應用之間的拖放。

此屬性的默認值在iPad上為true ,在iPhone上為false 在iPhone上將值更改為true可以將內容從表格視圖拖動到iPhone上的其他應用程序,並從其他應用程序接收內容。

以下代碼顯示了如何使用dragInteractionEnabled以允許iPhone上的UItableView進行拖放交互:

class TableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        /* ... */

        tableView.dragInteractionEnabled = true
    }

}

#2。 允許在iPhone上拖放UICollectionView交互

UICollectionView有一個名為dragInteractionEnabled的屬性。 dragInteractionEnabled具有以下聲明

var dragInteractionEnabled: Bool { get set }

一個布爾值,指示集合視圖是否支持應用程序之間的拖放。

此屬性的默認值在iPad上為true ,在iPhone上為false 在iPhone上將值更改為true可以將內容從集合視圖拖到iPhone上的其他應用程序,並從其他應用程序接收內容。

以下代碼顯示如何使用dragInteractionEnabled以允許在iPhone上進行UICollectionView拖放交互:

class CollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        /* ... */

        collectionView?.dragInteractionEnabled = true
    }

}

#3。 允許在iPhone上拖放UIImageView交互

UIDragInteraction有一個名為isEnabled的屬性。 isEnabled具有以下聲明

var isEnabled: Bool { get set }

一個布爾值,指定拖動交互是否響應觸摸並允許參與拖動活動。

以下代碼顯示了如何使用isEnabled以便除了在iPhone上的UIImageView drop交互之外允許拖動交互:

class ViewController: UIViewController, UIDragInteractionDelegate, UIDropInteractionDelegate {

    let imageView = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(imageView)
        imageView.image = UIImage(named: "MyImage")
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFit
        imageView.frame = view.bounds
        imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

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

        let dragInteraction = UIDragInteraction(delegate: self)
        dragInteraction.isEnabled = true
        imageView.addInteraction(dragInteraction)
    }

    /* ... */

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM