我正在按照this问题的已接受答案,但我在将数据从ViewControllerB
(第二个视图控制器)传递回ViewController
(初始视图控制器)时遇到问题。根据我添加的一些印刷语句的输出,我认为在ViewController
之前发生textFieldDidEndEditing
的展开。
dataPassed from ViewControllerB: Default passed data
newValue: Default passed data
textFieldDidEndEditing: Pass this back
我已成功将数据传回ViewController
,方法是在ViewControllerB
上设置按钮并设置dataPassed = textField.text
。我能够将此工作的另一种方法是将dataReceived = sourceViewController.dataPassed
更改为dataReceived = sourceViewController.textField.text
函数中的unwindToThisController
。但它看起来并不像上面提到的接受的答案的海报使用过这两种解决方法,而且我不确定这些解决方法中的任何一种是否是可以接受的方法。
我正在使用Xcode 8.2.1和Swift 3。
ViewController代码(初始视图控制器)
/* ViewController.swift */
import UIKit
class ViewController: UIViewController {
var dataReceived: String? {
willSet {
print("newValue: " + newValue!)
labelOne.text = newValue
}
}
@IBOutlet weak var labelOne: UILabel!
@IBAction func buttonOne(_ sender: UIButton) {
performSegue(withIdentifier: "viewNext", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
labelOne.text = "Default passed data"
}
// Segue ViewController -> ViewControllerB
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "viewNext" {
let viewControllerB = segue.destination as! ViewControllerB
viewControllerB.dataPassed = labelOne.text
}
}
// Segue ViewController <- ViewControllerB
@IBAction func unwindToThisControllerWithSegue(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? ViewControllerB {
print("dataPassed from ViewControllerB: " + sourceViewController.dataPassed!)
dataReceived = sourceViewController.dataPassed
//dataReceived = sourceViewController.textField.text
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ViewControllerB代码(第二个视图控制器)
/* ViewControllerB.swift */
import UIKit
class ViewControllerB: UIViewController, UITextFieldDelegate {
var dataPassed: String?
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
textField.text = dataPassed
textField.delegate = self
}
// Text field delegate methods
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
print("textFieldDidEndEditing: " + textField.text!)
dataPassed = textField.text
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 0 :(得分:0)
我是这个问题的提问者,幸运的是我有一个示例项目的备份,这是我在那里找到的。这就是我在第一个视图控制器中所做的事情
var displayValue: Double{
get{
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set{
display.text?="\(newValue)"
typing=false
}
}
@IBAction func unwind(segue: UIStoryboardSegue){
let foo = segue.sourceViewController as! viewControllerB
let a = foo.dataSent
displayValue = NSNumberFormatter().numberFromString(a!)!.doubleValue
}
它工作正常。也许如果你可以分享你正在研究的样本项目,我可以看出为什么它不起作用? :)