Aijaz.Ali90
Aijaz.Ali90

Reputation: 23

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

Upvotes: 0

Views: 502

Answers (3)

shraddha11
shraddha11

Reputation: 773

You have to inherit UIViewController subclass or UIViewController class. By doing that an error should be resolved.

Upvotes: 0

mutAnT
mutAnT

Reputation: 464

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)

Upvotes: 4

Andy
Andy

Reputation: 753

present(_:animated:completion:) is a method of UIViewController, so it must be called on some type of UIViewController.

If your class is initially created by a view controller, then you could try passing in a reference using the delegation pattern:

Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled.

If you created a protocol for your custom class something like this:

protocol MyClassDelegate {
    func shareAppLink()
}

Then you could conform to that protocol in your View Controller and call the method something like this: delegate.shareAppLink()

Upvotes: 1

Related Questions