我得到了代码,但它不起作用,让我知道我是否做错了什么。 在代码中我有一个imageview,我以编程方式创建并将图像添加到uiview.Right现在我无法加载图像"拖动视图"。
func longPressed(_ sender : UILongPressGestureRecognizer){
let locationInView = sender.location(in: self.view)
let cell = sender.view as? ParamterCollectionViewCell
var tImageView: UIImageView!
tImageView.frame = CGRect(x:0, y:0, width: 30 , height:30)
tImageView.image = parameterImageArray[0]
switch sender.state {
case .began:
// create an NSData object from myView
let archive = NSKeyedArchiver.archivedData(withRootObject: tImageView!)
// create a clone by unarchiving the NSData
draggingView = NSKeyedUnarchiver.unarchiveObject(with: archive) as? UIView
self.view.addSubview(draggingView!)
draggingView!.center = locationInView;
self.view.bringSubview(toFront: draggingView!)
break
case .changed:
if (contentView.frame.contains(locationInView)) {
draggingView?.center = locationInView;
}
break
case .ended:
break
default:
break
}
} }
答案 0 :(得分:0)
尝试一下......在想法上与你的代码非常相似,但我认为它可能会更好一些方法:
func longPressed(_ sender : UILongPressGestureRecognizer) {
let locationInView: CGPoint = sender.location(in: self.view)
let locationInCollectionView: CGPoint = sender.location(in: self.collectionView)
if sender.state == .began {
if let indexPath: IndexPath = self.collectionView.indexPathForItem(at: locationInCollectionView) {
if let cell = self.collectionView.cellForItem(at: indexPath) {
UIGraphicsBeginImageContext(cell.bounds.size)
cell.layer.render(in: UIGraphicsGetCurrentContext()!)
let cellImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.movingCellImageView = UIImageView(image: cellImage)
self.movingCellImageView?.alpha = 0.75
self.view.addSubview(self.movingCellImageView!)
self.movingCellImageView?.center = locationInView
}
}
}
// Move movingCellImageView following finger position
if sender.state == .changed {
self.movingCellImageView?.center = locationInView
}
// Remove movingCellImageView when ended
if sender.state == .ended {
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
self.movingCellImageView?.alpha = 0
}, completion: { (success: Bool) in
self.movingCellImageView?.removeFromSuperview()
self.movingCellImageView = nil
})
}
}
参考文献:
Tim Puckett - https://adoptioncurve.net/archives/2014/07/creating-a-draggable-uicollectionviewcell/
Chan Jing Hong迅速实施 http://eatliftswift.weebly.com/technical/creating-a-draggable-uicollectionviewcell