提问者:小点点

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


我制作了一个类question2

class Question2 {

@IBOutlet var imageView: UIImageView!
var textField: UITextField?
var textField2: UITextField?

init(img: UIImage, txt: String, txt2: String) {
    imageView?.image = img
    self.textField?.text = txt
    self.textField2?.text = txt2
    
} }

在另一个类中Question2Brain

class Question2Brain {

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

正如您所看到的,我创建了这个数组,并将UImages与txt和txt2一起放置在其中。简单地说,我要向用户显示一个图像,然后输入一个描述图像的输入,然后检查它是否匹配txt和txt2。在运行模拟器时,我得到以下错误:

***由于未捕获异常“nSunKnownKeyException”而终止应用程序,原因:“[SetValue:ForUndefinedKey:]:对于密钥ImageView,此类不符合密钥值编码。”使用NSException类型的未捕获异常终止

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


共1个答案

匿名用户

您的Question2类是UIViewController的子类,但您只是创建它的实例,而没有引用情节提要,因此出口将为nil

创建一个视图控制器的多个实例并将它们放在数组中是没有意义的。

您应该使用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")
] }