iOS 更改呈现 View Controller 上的按钮文本

标签 ios swift uiviewcontroller

我在 View Controller 方面有一个相当复杂的设置。我的理由超出了这个问题的范围。所以我有 3 个 View Controller 。

在这种情况下,ViewControllerA 是主视图 Controller 。 ViewControllerB 是从 ViewControllerA 显示的容器 View Controller 。 ViewControllerB 有一个按钮,它有一个 segue 来显示 ViewControllerC。然后在 ViewControllerC 中有一个按钮可以关闭以返回。

ViewController 的 A 和 B 可以不同。取决于用户是在编辑对象还是在创建新对象。我所说的事情在这两种情况下保持一致。

基本上,我的目标是当用户关闭 ViewControllerC 时,它会更改 ViewControllerB 上的按钮文本。取决于用户对 ViewControllerC 的操作。

我正在考虑以某种方式使用 self.presentingViewController,但我不知道如何访问 ViewControllerB 中的特定按钮。

关于如何实现此目标的任何想法?

最佳答案

我建议你使用一个协议(protocol)来定义一个通用的方法来更新按钮文本。两个 ViewControllerB 都可以遵循这个协议(protocol)。然后使用委托(delegate)回调方法从您的 ViewControllerC 调用这些方法。

当您从 ViewControllerB 呈现 ViewControllerC 时,您可以在呈现之前将 delegate 属性设置为 self。根据您呈现 ViewControllerC 的方式,您可以在不同的地方执行此操作。正如您所说,您正在使用 segue 来执行此操作,那么您应该在 prepareForSegue 方法中执行此操作。

  1. 声明一个协议(protocol),它定义了一种更新按钮文本的方法,如下所示:
protocol ChangeableButtonTextViewController {
    func updateButtonText(newText: String)
}

然后让你的EditViewControllerB和CreateViewControllerB符合这个协议(protocol)来更新按钮文本:

class EditViewControllerB: UIViewController, ChangeableButtonTextViewController {
    func updateButtonText(newText: String) {
        button.text = newText
    }

    // Other stuff in your ViewController
}
  1. 像这样向 ViewControllerC 添加一个 delegate 属性:

var delegate: ChangeableButtonTextViewController?

  1. 向 EditViewControllerB 和 CreateViewControllerB 添加一个 prepareForSegue 方法,它看起来像这样:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      segue.destination as! ViewControllerC).delegate = self
}
  1. 然后您可以在 ViewControllerC 中执行类似的操作:
func dismiss() {
    delegate.updateButtonText("NewText")
}

如果您需要任何进一步的说明,请告诉我。

关于iOS 更改呈现 View Controller 上的按钮文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44638017/

相关文章:

ios - 创建 NSDateFormatter 可重用类

Swift:如何隐藏/显示 `didSelectRowAt indexPath` 部分中的行

swift - NSNumberFormatter 货币 : "plusSign" replaces currency

iOS:具有许多 UIViewControllers 的 UIScrollView 中的内存管理

ios - 如何仅在首次启动 IOS Swift 时显示页面 Controller

iphone - 如何正确显示 UIViewController?

ios - 单个 ViewModel 的多个 View (iOS)

ios - 试图从文档目录中删除文件

ios - 是否可以将旧的 xcode 代码更新为最新的 xcode?

ios - Swift 位置返回 nil