Search code examples
iosswiftswift3

How to present a new screen without a UIViewController in Swift 4?


I have not implemented UIViewController because I have already inherited from another class, and it gives the error that present is not a member of this class

func shareAppLink() {           
    let name = "http://aijaz.com"
    let items = [name] as [Any]

    let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
    present(ac, animated: true)     
}

Solution

  • You can also use Respoder Chain to get the parent view controller for a view

    extension UIView {
        var parentViewController: UIViewController? {
            var parentResponder: UIResponder? = self
            while parentResponder != nil {
                parentResponder = parentResponder!.next
                if let viewController = parentResponder as? UIViewController {
                    return viewController
                }
            }
            return nil
        }
    }
    

    And declare your shareAppLink function like

    func shareAppLink(sender : UIView) {
        let name = "http://aijaz.com"
        let items = [name] as [Any]
        let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
        sender.parentViewController(ac, animated: true)
    }
    

    then in didSelectRowAt, you can call it as:

    self.shareAppLink(sender : cell)