繁体   English   中英

如何将变量分配给 Swift 中的 UIInteraction?

[英]How can a variable be assigned to a UIInteraction in Swift?

为什么我需要变量? 因为在单元格中进行 2 次不同的长按时,需要在func contextMenuInteraction中调用 2 个图像

下面是我的代码,我在其中为每个长按交互分配了一个变量。 我收到错误Thread 1: Swift runtime failure: Unexpectedly found nil while implicitly unwrapping an Optional value

//在scope

var dd : UIInteraction!
var cc : UIInteraction!
@IBOutlet weak var immy: UIImageView!

//在 override func awakeFromNib() 和一个 objC 分别长按 function

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

下面是调用 2 个交互的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
                  }
            })
            }

意外发现 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 {
...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM