Search code examples
iosobjective-cswiftnsobjectuicontextmenuinteraction

How can a variable be assigned to a UIInteraction in Swift?


Why do I need variables? Because upon 2 different long presses in the cell, there are 2 images that need to be called in func contextMenuInteraction

Below is my code, where I assign a variable to each long press interaction. I get error Thread 1: Swift runtime failure: Unexpectedly found nil while implicitly unwrapping an Optional value

//In scope

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

//In override func awakeFromNib() and an objC long press function respectively

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

Below is the func ContextMenuInteraction where the 2 interactions get called

    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
                  }
            })
            }

Where does the error unexpected found nil occur - In this line:

immy.addInteraction(dd)

Solution

  • Update this has been solved (not by me - someone on 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 {
    ...
    }