【发布时间】:2016-10-23 18:35:41
【问题描述】:
我想将工作表中的数据传递回 ViewController。
我尝试使用委托,但它不起作用,因为当我关闭工作表 (self.dismiss(self)) 时,后面的 ViewController 没有刷新。
【问题讨论】:
标签: swift xcode macos cocoa swift3
我想将工作表中的数据传递回 ViewController。
我尝试使用委托,但它不起作用,因为当我关闭工作表 (self.dismiss(self)) 时,后面的 ViewController 没有刷新。
【问题讨论】:
标签: swift xcode macos cocoa swift3
您将不得不使用称为 NSNotificationCenter 的单例类
在调用 ViewController 类中的 presentViewController 方法之前添加此语句
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.funcToBeExecuted(_:)), name:String, object: nil)
在Sheet类中dismissViewController之前添加此语句
NSNotificationCenter.defaultCenter().postNotificationName(String, object: AnyObject?, userInfo: [NSObject : AnyObject]?))
所以从技术上讲,这就是它的工作原理。您在应用程序中设置一个观察者,等待应用程序何时执行#selector 方法。当应用程序执行 postNotification 语句时,内存中具有与 postNotification 相同的 NotificationName 的所有观察者都会被触发并实现它们分配的#selectors。
参数中的 postNotificationName 中的 userInfo 有助于将数据从一个地方传递到另一个地方,甚至传递给同名的多个观察者。因此,在 NSNotification 选择器要执行的方法中,我们可以访问 userInfo,如下所述。
func funcToBeExecuted(notification: NSNotification)
{
let receivedData = notification.userInfo
}
这应该对你有用。
【讨论】: