swift - ViewDidAppear 不会自动调用

标签 swift macos appkit nsviewcontroller

我有一个 HomeViewController 正在使用 segue 打开一个 WelcomeViewController 并且来自 Sheet 类型。

WelcomeViewController 中,用户正在输入信息,然后关闭(关闭)它。 WelcomeViewController 关闭后,我想通过更改 TextFieldString 值来更新 HomeViewController

问题是,HomeViewController 中的 ViewDidAppear 在关闭 WelcomeViewController 后不会被调用。我以前在为 iOS 开发时没有遇到过这个问题。

我该如何解决这个问题?我尝试手动调用它但遇到了问题,因为我的 IBOutlets 设置为 nil 并且我无法更改我的 TextField 中的文本。

这是调用 segue 的代码:

self.performSegue(withIdentifier: "welcome", sender: self)

这是我在 HomeViewController 中的 viewDidAppear:

override func viewDidAppear() {
   super.viewDidAppear()
   if (CoreDataAccess().countUsers() == 0) {
       self.performSegue(withIdentifier: "welcome", sender: self)
   } else {
       //continue execution..
   }
}

WelcomeViewController 中,我使用这段代码关闭了 ViewController

dismiss(self)

最佳答案

这就是我使用 delegate 解决它的方法。 感谢@ullstrm 的建议。

首先我将这个协议(protocol)添加到 HomeViewController

protocol WelcomeDelegate {
    func insertData(_ name: String, birthday: Date)
}

然后这个prepare(for segue:)

override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
    if let destinationViewController = segue.destinationController as? WelcomeViewController {
        destinationViewController.delegate = self
    }
}

这个扩展在底部(我知道手动调用 viewDidAppear 是不行的,但它现在可以工作)

extension HomeViewController : WelcomeDelegate {
    func insertData(_ name: String, birthday: Date) {
        viewDidAppear()
    }
}

然后在 WelcomeViewController 中我添加了这个变量

var delegate:WelcomeDelegate? = nil

这行就在 dismiss(self) 之前

self.delegate?.insertData(tfName.stringValue, birthday: dpAge.dateValue)

关于swift - ViewDidAppear 不会自动调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53191404/

相关文章:

swift - 如何在 API Weather - Sunrise/Sunset 中用 swift 代码转换数据?

快速最大连续正数

swift - macOS - 如何让 NSSavePanel 在文件名中添加文件扩展名?

macos - Docker推送到Amazon ECR会减慢或卡住

objective-c - 激活热键快捷记录器

ios - 如何在 swift 中用 nsattribute 替换 html 标签?

ios - 使用 RxSwift 从后台进入前台时 AVPlayer 自动播放

c++ - C++ stderr 输出在 OSX 中的哪里?

cocoa - 如何在 Cocoa AppKit 应用程序中实现缩放/缩放

objective-c - NSTextField - 如何更改文本/编辑区域的大小和位置?