Swift: 当两个视图彼此没有直接联系时,是否可以使用委托?
Swift: Is it possible to use delegation when both views aren't in direct connection with each other?
我有三个 ViewController:ViewController1、ViewController2 和 ViewController3。
ViewController1 在屏幕上推送 ViewController2,两个视图可以通过委托相互交互。
ViewController2 将 ViewController3 推到屏幕上。
现在可以在ViewController1和ViewController3之间建立一个委托吗?我希望 ViewController3 能够操作 ViewController1 的标签。
这种情况下的最佳方式是 Notification
模式
// Notification posting
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "fromViewController3"), object: nil, userInfo: myDict)
// Register in ViewController1 to receive notification in your class ViewController1
NotificationCenter.default.addObserver(self, selector: #selector(self.manipulateMyLabel(_:)), name: NSNotification.Name(rawValue: "fromViewController3"), object: nil)
// handle notification
func manipulateMyLabel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let newString = dict["labelValue"] as? String {
// user newString to update the label text or something.
}
}
}
我有三个 ViewController:ViewController1、ViewController2 和 ViewController3。
ViewController1 在屏幕上推送 ViewController2,两个视图可以通过委托相互交互。
ViewController2 将 ViewController3 推到屏幕上。
现在可以在ViewController1和ViewController3之间建立一个委托吗?我希望 ViewController3 能够操作 ViewController1 的标签。
这种情况下的最佳方式是 Notification
模式
// Notification posting
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "fromViewController3"), object: nil, userInfo: myDict)
// Register in ViewController1 to receive notification in your class ViewController1
NotificationCenter.default.addObserver(self, selector: #selector(self.manipulateMyLabel(_:)), name: NSNotification.Name(rawValue: "fromViewController3"), object: nil)
// handle notification
func manipulateMyLabel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let newString = dict["labelValue"] as? String {
// user newString to update the label text or something.
}
}
}