简体   繁体   中英

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

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM