是否可以在对象数组中使用 UIImage?

Is It Possible to Use UIImage Inside an Array of Objects?

我做了一个结构Question

struct Question {

let imageView: UIImage
let textField: String
let textField2: String }

class SpellingViewController

class SpellingViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var theImage: UIImageView!
@IBOutlet weak var theInput: UITextField!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var progBar: UIProgressView!

var spellingScore: Int64 = 0
var questionNum = 0

let question = [
    Question2(imageView: UIImage(named: "BeardQ")!, textField: "Beard", textField2: "beard"),
    Question2(imageView: UIImage(named: "CastleQ")!, textField: "Castle", textField2: "castle"),
    Question2(imageView: UIImage(named: "CloudQ")!, textField: "Cloud", textField2: "cloud"),
    Question2(imageView: UIImage(named: "Elephant")!, textField: "Elephant", textField2: "elephant"),
    Question2(imageView: UIImage(named: "RainQ")!, textField: "Rain", textField2: "rain")
] }

如您所见,我创建了这个数组并将 UIImages 与 textField 和 textField2 一起放入其中。简单地说,我要向用户显示一个图像,我将接受描述该图像的输入并检查它是否与 textField 和 textField2 匹配。 运行 模拟器时,出现以下错误:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x7f9987017e80> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key imageView.' terminating with uncaught exception of type NSException

是因为我在数组中使用了 UIImage 吗?

您的 Question2 class 不是 UIViewControllerUIView 的子 class,因此创建 [=14] 没有意义=] 里面有。

当从故事板或 nib 文件创建视图控制器或视图时设置插座。你没有那样做,所以这些渠道没有任何价值。

为了您的目的创建多个视图实例并将它们放在一个数组中是没有意义的。

您应该使用 Question 结构,然后将该结构的实例提供给可以显示它的视图控制器。

struct Question {
   let image: UIImage
   let txt: String
   let txt2: String
}

let question = [
    Question(img: UIImage(named: "BeardQ")!, txt: "Beard", txt2: "beard"),
    Question(img: UIImage(named: "CastleQ")!, txt: "Castle", txt2: "castle"),
    Question(img: UIImage(named: "CloudQ")!, txt: "Cloud", txt2: "cloud"),
    Question(img: UIImage(named: "Elephant")!, txt: "Elephant", txt2: "elephant"),
    Question(img: UIImage(named: "RainQ")!, txt: "Rain", txt2: "rain")
] }

视图控制器将具有出口,您将根据提供给它的 Question 分配这些出口的内容。

关于未定义键的异常表明您的故事板或笔尖指定了 UIView 的 class(没有任何出口属性)而不是任何子 class您已使用这些 IBOutlet 属性创建

根据您收到的错误消息:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x7f9987017e80> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key imageView.' terminating with uncaught exception of type NSException"

几乎可以肯定您的界面中某处有一个 UIView class,其中 属性 imageView 无效。我建议对字符串 imageView 进行多文件搜索。将搜索设置为整个单词,区分大小写。它在故事板和源文件中查找字符串,因此您应该能够通过这种方式找到它。