【发布时间】:2017-10-11 08:48:45
【问题描述】:
我已经成功地通过委托函数在视图控制器之间传递了一段数据(一个 String 变量、一个 Int 变量等)。但是,我还没有设法通过委托函数传递各种数据。
我收到以下错误:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x7faea770db60> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key receivingAmountLabel.'
如果我删除 receingAmountLabel,错误会转到另一个 UI 元素。如果我删除该元素,它会继续到另一个。
所有 UI 元素都按应有的方式连接。相关的代码如下所示:
FirstVC.swift 类 FirstVC: UIViewController, DataSentDelegateMax {
@IBOutlet weak var receivingStringLabel: UILabel!
@IBOutlet weak var receivingAmountLabel: UILabel!
func userDidEnterData(stringData: String, amountData: Int) {
receivingStringLabel.text = stringData
receivingAmountLabel.text = String(amountData)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "showSecondVC") {
let secondVC = segue.destination as! SecondVC
secondVC.delegate = self
}
}
SecondVC.swift
protocol DataSentDelegateMax {
func userDidEnterData(stringData: String, amountData: Int)
}
@IBOutlet weak var stringTF: UITextField!
@IBOutlet weak var amountTF: UITextField!
var delegate: DataSentDelegateMax? = nil
@IBAction func sendButtonAction(_ sender: Any) {
if delegate != nil {
if (stringTF.text != nil) {
if (Int(amountTF.text!) != nil) {
let stringData = stringTF.text
let amountData = Int(amountTF.text!)
delegate?.userDidEnterData(stringData: stringData!, amountData: amountData!)
dismiss(animated: true, completion: nil)
}
}
}
}
尝试在委托中传递字典时遇到同样的问题。
【问题讨论】:
-
您没有在 Interface Builder 中设置正确的
UIViewController类。仍然是UIViewController,而不是FirstVC。如果这是由于错误的连接(重命名等)造成的,它应该有[< FirstVC 0x7faea770db60> setValue:forUndefinedKey:]:而不是[<UIViewController 0x7faea770db60> setValue:forUndefinedKey:]: -
您可以通过移除并重新连接 IBOutlets 再试一次吗?
-
此错误通常发生在 xib 或故事板中的 IBOutlets 无效时(如果它们已设置然后重命名或删除等...)。如前所述,检查您的 IB 文件中是否存在无效引用。
-
@Larme,它是正确的,但我更改了两个视图控制器的自定义类,然后分别更改回 FirstVC SecondVC 并且它工作。感谢您的帮助!