[英]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,根據您的需要,您可以選擇以下方法之一來解決您的問題。
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
}
}
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
}
}
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.