如何将变量赋值给Swift中的UIInteraction ?



为什么我需要变量?因为在单元格中有两次不同的长按,在func contextMenuInteraction

中有两个图像需要调用下面是我的代码,其中我为每个长按交互分配了一个变量。我得到错误Thread 1: Swift runtime failure: Unexpectedly found nil while implicitly unwrapping an Optional value

//范围
var dd : UIInteraction!
var cc : UIInteraction!
@IBOutlet weak var immy: UIImageView!

//在覆盖函数awakeFromNib()和一个objC长按函数分别

immy.addInteraction(dd) // (this is in the override nib)
self.like.addInteraction(self.cc) //(this is in the @objc func didLongPress())

下面是func ContextMenuInteraction,其中两个相互作用被称为

func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
UIContextMenuConfiguration(identifier: nil, previewProvider: {

if self.dd as! NSObject == interaction {
if let unwrappedImage = self.immy.image {
return ImagePreviewController(image:unwrappedImage)

}
else {
return nil
}
// put dd stuff here
} else if self.cc as! NSObject == interaction {
// put cc stuff here
let image3 = UIImage(named:"ring-309550-2.png")
if let unwrappedImage1 = image3 {
return ImagePreviewController(image:unwrappedImage1)

}
else {
return nil
}
}
else {
return nil
}
})
}

哪里出现了意想不到的错误:

immy.addInteraction(dd)

更新这个问题已经解决了(不是我- reddit上有人)

// scope
var dd: UIContextMenuInteraction
var cc: UIContextMenuInteraction
// inside init()
self.dd = UIContextMenuInteraction(delegate: self)
self.cc = UIContextMenuInteraction(delegate: self)
// downstream
image1.addInteraction(dd)
image2.addinteraction(cc)
// inside contextMenuInteraction()
if self.dd == interaction {
...
} else if self.cc == interaction {
...
}

最新更新