[英]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我没有实现 UIViewController 因为我已经从另一个类继承了它,它给出了当前不是这个类的成员的错误
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您还可以使用 Respoder Chain 获取视图的父视图控制器
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并声明您的 shareAppLink 函数,例如
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:然后在 didSelectRowAt 中,您可以将其称为:
self.shareAppLink(sender : cell)
present(_:animated:completion:)
is a method of UIViewController
, so it must be called on some type of UIViewController
. present(_:animated:completion:)
是UIViewController
一个方法,所以它必须在某种类型的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()
然后你可以在你的视图控制器中遵守该协议并调用这样的方法:
delegate.shareAppLink()
You have to inherit UIViewController subclass or UIViewController class.您必须继承 UIViewController 子类或 UIViewController 类。 By doing that an error should be resolved.
通过这样做,应该可以解决错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.