ios - 在第一个 View Controller 的标签中显示输入到文本字段(在第二个 View Controller 中)的文本?

标签 ios swift

我一直在尝试单独使用 Swift 以编程方式完成挑战——不使用 Storyboard。

我的第一个 View Controller 有一个标签和一个按钮可以转到第二个 View Controller 。

我在 app delegate 文件中创建了一个导航 Controller ,然后在按下按钮时推送到第二个 View Controller 。

第二个 View Controller 有一个文本框、一个保存文本的按钮和一个返回第一个 View Controller 的按钮。

UI 很好,但我不知道如何保存输入到第二个 View Controller 上的文本字段中的文本,然后在第一个 View Controller 的标签中显示该文本。

有人可以告诉我如何执行此操作吗?

目前在我的按钮中返回到第一个 View Controller 我有这个:

func handleBackToVC1() {

        self.navigationController?.popViewController(animated: true)
    }

这是我传递文本字段中的数据并将其显示在标签中的地方吗? 另外,我应该给标签一些文字作为开始吗?但是,哪些内容会更改为输入到文本字段中的内容?

最佳答案

使用协议(protocol)委托(delegate)将数据从 SecondViewController 传递到 FirstViewController

protocol TextFieldDataDelegate: class {
    func saveText(_ text: String)
}

class SecondViewController: UIViewController {
   weak var delegate: TextFieldDataDelegate?

  //on save button tap call the delegate method
  delegate?.saveText(textField.text)
}

//set FirstViewController as delegate for TextFieldDataDelegate protocol

class FirstViewController: UIController, TextFieldDataDelegate {

 // when you create instance of SecondViewController assign the delegate as self
 let secondVC = SecondViewController()
 secondVC.delegate = self

  //in saveText set label text as passed from SecondVC
  func saveText(_ text: String) {
    self.textLabel.text = text
  }
}

注意:类似this这样的问题还有很多, 在提问之前总是搜索。谢谢

关于ios - 在第一个 View Controller 的标签中显示输入到文本字段(在第二个 View Controller 中)的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453373/

相关文章:

ios - 如何向 Collection View 单元格的内底边缘添加阴影? swift 3

swift - 无法在 Swift 中使用 KeyType 类型的参数列表调用方法

iphone - 在所有设备尺寸上将 UIVIEW 居中

快速查询搜索附加数组

ios - 显示错误,因为需要符合协议(protocol)

ios - 使用协议(protocol)传递数据

swift - 从字符串中提取特定的字符串模式(swift 2)

ios - 获取有关 YouTube 视频的信息

ios - 自定义 View Controller 转换偶尔崩溃

ios - 枚举值未正确显示