首页 > 解决方案 > 按下单元格内的图像时显示 ViewController

问题描述

我不知道如何以编程方式呈现 viewController

我已经完成了一个用于点击图像的功能。我现在唯一的问题是如何呈现 viewController。图像在单元格内。

ItemsCell.swift

let tapGesture = UITapGestureRecognizer()

                if let imageStr = obj.image {

                    item.optionImage.kf.setImage(with:URL(string:imageStr))
                    item.optionImage.isUserInteractionEnabled = true
                    tapGesture.addTarget(self, action: #selector(tappedImage))
                    item.optionImage.addGestureRecognizer(tapGesture)

                } else {

                    item.optionImage.image = nil

                }

功能:

@objc func tappedImage() {

        print("image tapped")

//        let storyboard = UIStoryboard(name: "Main", bundle: nil)
//        let controller = storyboard.instantiateViewController(withIdentifier: "AssetsViewController")

//        controller.present(controller, animated: true, completion: nil)  
    }

标签: iosswift

解决方案


利用Post Notification

class VC: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(presentVC(_:)), name: NSNotification.Name("PresentVCNotificationName"), object: nil)
    }

    @objc
    func presentVC(_ notification: Notification) {
        let cell = notification.object as? YourCell

        let storyboard = UIStoryboard(name: "Your Storyboard Name", bundle: Bundle.main)
        let vc = storyboard.instantiateViewController(withIdentifier: "Your Storyboard ID")
        self.present(vc, animated: true, completion: nil)
    }

    deinit {
       NotificationCenter.default.removeObserver(self)
    }
}


class Cell: UITableViewCell {

   @objc func tappedImage() {

      NotificationCenter.default.post(name: NSNotification.Name("PresentVCNotificationName"), object: self)
   }
}

推荐阅读