[英]How to call method from another class in swift
我有一个带有collectionView的viewcontroller类ViewController
。 我还有单例类FacebookManager
从FacebookManager
获取数据。
我想要做的是在facebook类中运行一个方法,然后在ViewController中调用一个方法来重新加载collectionView。
我尝试通过设置在Facebook管理器中引用ViewController
class FacebookManager {
static let sharedInstance = FacebookManager()
var vc:ViewController?
}
然后在ViewController中设置
class ViewController: {
func viewDidLoad() {
FacebookManager.sharedInstance.vc = self
}
}
然后在FacebookManager中调用
func myMethod() {
vc.collectionView.reloadData()
}
但这不起作用。
怎么做得好?
要提供两个或多个类之间的通信,建议使用两种方法。 1)授权2)通知
在您给定的实现委托方法的代码中,我们必须在FacebookManager中创建协议和委托属性。 并将视图控制器指定为FacebookManger的委托
例:
protocol FacebookManagerDelegate: class {
func refreshData()
}
class FacebookManager {
var weak delegate:FacebookManagerDelegate?
func myMethod() {
delegate?.refreshData()
}
}
class ViewController: FacebookManagerDelegate {
ViewDidLoad() {
FacebookManager.sharedInstance.delegate = self
}
func refreshData() {
self.collectionView.reloadData()
}
}
但是你正在使用singleton类,因此将来多个类将使用这个类,如果你想通知多个类使用Notification方法,这很容易实现,应该在singleton类中使用
每当您想要通知时,都会在FacebookManger中发布通知:
class FacebookManager {
func myMethod() {
NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil)
}
}
class ViewController {
ViewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(reloadData(_:)), name: NotificationName, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func reloadData(notification: NSNotification) {
self.collectionView.reloadData()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.