Search code examples
swiftuiimageviewuiactivityviewcontroller

Show the UIActivityViewController in own class


i am working on my app and want to share an image. First i want to present the UIActivityViewController from my own class called "PostCell" (the class to handle my prototype-cell). I get the message "Use of unresolved identifier 'present'" (see the picture below). How can i call the vc correctly in my class?

Second i want to share the actual image which is in my postImageView: UIImageView! in the PostCell. Do i have to use IndexPath for the right image ?

Can you please help. THX a lot.

import UIKit

class PostCell: UITableViewCell {

@IBOutlet weak var postCaptionLabel: UILabel! @IBOutlet weak var postImageView: UIImageView! @IBOutlet weak var stuffButton: UIButton! @IBAction func shareButton(_ sender: UIButton) { if let image = UIImage(self.postImageView.image) { let vc = UIActivityViewController(activityItems: [image], applicationActivities: []) present(vc, animated: true) } }...

enter image description here


Solution

  • First, UITableViewCell does not have present method. That has to be done from the ViewController or create a reference in the cell to the ViewController and then call present. Second, self.postImageView.image will already give you a UIImage there is no need to construct it. Here is an example.

    import UIKit
    
    
    class PostCell: UITableViewCell {
    
    @IBOutlet weak var postCaptionLabel: UILabel!
    
    @IBOutlet weak var postImageView: UIImageView!
    
    @IBOutlet weak var stuffButton: UIButton!
    
    // Here you add a reference to the viewController. Remember to write cell.viewController = self in the cellForRow method
    
    var viewController : UIViewController!
    
    @IBAction func shareButton(_ sender: UIButton) {
    
        // Here you remove the UIImage constructor.
        if let image = self.postImageView.image {
            let vc = UIActivityViewController(activityItems: [image], applicationActivities: [])
            viewController.present(vc, animated: true)
        }
    
    }...