gpt4 book ai didi

ios - 如何在模态 Viewcontroller 被解散后更新父 Viewcontroller 的 View

转载 作者:行者123 更新时间:2023-11-28 10:30:35 25 4
gpt4 key购买 nike

我有一个 UIBarButtonItem ,当它被关闭时,我想从模式 viewController 的值更新它。目前我只能通过获取当前可见的 viewController 来做到这一点,这是我不知道的'想要。有没有一种方法可以在关闭模态视图 Controller 后更新父 View Controller 。

class HomeViewController: UIViewController {

@IBOutlet weak var accountButton: UIBarButtonItem!

override func viewWillAppear(_ pAnimated: Bool) {
super.viewWillAppear(pAnimated)
self.accountButton.title = User.current!.firstName
}

@IBAction func accountButton(_ pSender: UIBarButtonItem) {
let editUserAccountVC = UIStoryboard.fs_instantiateFromStoryboard("Main", identifier: "EditUserAccountViewController") as! EditUserAccountViewController
let navVC = UINavigationController(rootViewController: editUserAccountVC)
navVC.view.tintColor = self.view.tintColor
self.present(navVC, animated: true)
}
}
}

这是编辑后关闭的模态

class EditUserAccountViewController: UIViewController {

var firstName: String?

@IBAction func saveButton(_ sender: Any) {
self.dismiss(animated: true) {
if let thePresentedViewController = self.presentingViewController as? HomeViewController {
thePresentedViewController.accountButton.title = self.firstName
}
}
}
}

最佳答案

我认为您应该在模态 Controller 实例中存储对父 Controller 的引用。您可以使用协议(protocol)使其更通用。声明以下协议(protocol):

protocol AccountButtonProvider: AnyObject {
var accountButtonTitle: String? { set get }
}

AnyObject 需要将对 AccountButtonProvider 的引用声明为 weak。我想您将需要它来避免内存泄漏。

使 HomeViewController 符合 AccountButtonProvider:

extension HomeViewController: AccountButtonProvider {
var accountButtonTitle: String? {
set {
accountButton.title = newValue
}
get {
return accountButton.title
}
}
}

然后将以下属性添加到 EditUserAccountViewController:

weak var accountButtonProvider: AccountButtonProvider?

在呈现 EditUserAccountViewController 之前初始化此属性。为此,将 editUserAccountVC.accountButtonProvider = self 添加到 accountButton(_:):

@IBAction func accountButton(_ pSender: UIBarButtonItem) {
let editUserAccountVC = UIStoryboard.fs_instantiateFromStoryboard("Main", identifier: "EditUserAccountViewController") as! EditUserAccountViewController
editUserAccountVC.accountButtonProvider = self
}

你还应该修改saveButton(_:):

@IBAction func saveButton(_ sender: Any) {
self.dismiss(animated: true) {
self.accountButtonProvider?.actionButtonTitle = self.firstName
}
}

本文中的所有代码都在 Xcode 10.2.1 中进行了测试。我使用的是 Swift 5。

关于ios - 如何在模态 Viewcontroller 被解散后更新父 Viewcontroller 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56183412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com