我有 2 个 UIViewControllers
,我尝试使用 Notifications
和 观察者
。
这是我第一次使用这种设计模式,我有点困惑。我做错了什么?
我想指定只有当我从第二个 ViewController 单击后退按钮时,我才第一次从该打印中获取消息。
之后,当我单击 Go Next
时,消息正常,但 UILabel
没有隐藏或颜色改变。
这是我的第一个 UIViewController
代码:
class ReviewPhotosVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.post(name: Notification.Name("NotificationOfReviewMode"), object: nil)
}
@IBAction func goNextTapped(_ sender: UIButton) {
let fullscreenVC = storyboard?.instantiateViewController(withIdentifier: "FullscreenPhoto") as! FullscreenPhotoVC
self.present(fullscreenVC, animated: true, completion: nil)
}
}
这是我的第二个 UIViewController
代码:
class FullscreenPhotoVC: UIViewController {
@IBOutlet weak var customLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(hideCustomLabel),
name: Notification.Name("NotificationOfReviewMode"),
object: nil)
}
@IBAction func goBackTapped(_ sender: UIButton) {
let reviewPhotosVC = storyboard?.instantiateViewController(withIdentifier: "ReviewPhotos") as! ReviewPhotosVC
self.present(reviewPhotosVC, animated: true, completion: nil)
}
@objc func hideCustomLabel(){
customLabel.isHidden = true
customLabel.textColor = .red
print("My func was executed.")
}
}
这是我的 Storyboard:
感谢您阅读本文。
最佳答案
问题是您在下一个 Controller 初始化并开始观察之前发布通知。此外,不需要通知,您可以直接进行。在这种情况下,我使用了一个额外的变量 shouldHideLabel
因为你不能直接调用函数 hideCustomLabel()
因为这会导致崩溃,因为 socket 只在 View 加载后初始化.
class ReviewPhotosVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//NotificationCenter.default.post(name: Notification.Name("NotificationOfReviewMode"), object: nil)
}
@IBAction func goNextTapped(_ sender: UIButton) {
let fullscreenVC = storyboard?.instantiateViewController(withIdentifier: "FullscreenPhoto") as! FullscreenPhotoVC
fullscreenVC.shouldHideLabel = true
self.present(fullscreenVC, animated: true, completion: nil)
}
}
class FullscreenPhotoVC: UIViewController {
var shouldHideLabel = false
@IBOutlet weak var customLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if shouldHideLabel {
hideCustomLabel()
}
/*
NotificationCenter.default.addObserver(self,
selector: #selector(hideCustomLabel),
name: Notification.Name("NotificationOfReviewMode"),
object: nil)
*/
}
@IBAction func goBackTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
@objc func hideCustomLabel() {
customLabel.isHidden = true
customLabel.textColor = .red
print("My func was executed.")
}
}
关于ios - 如何使用通知和观察者从另一个 UIViewController 隐藏 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55727517/