问题描述
我正在使用标签栏控制器,并且试图从其他标签栏视图控制器访问默认值.我尝试了另一种功能(也显示在下面)中,并且效果很好,但是由于某种原因,它在这里不起作用.每当调用此代码时,它都会提出错误: FirstViewController().defaults
.有人知道为什么会这样吗?
I am using a tab bar controller and I'm trying to access the defaults from my other tab bar view controller. I tried this in a different function, also shown below, and it works perfectly, but for some reason it isn't working here. It puts up the error whenever this is called: FirstViewController().defaults
. Does anybody have any idea why this is happening?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = TableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
TableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
var photo: Photo
let description = FirstViewController().description
if(searchController.isActive){
photo = self.filteredPhotos[indexPath.row]
} else {
photo = self.photosArray[indexPath.row]
}
cell.textLabel!.text = photo.name
if(FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage != nil){
cell.imageView?.image = FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage
}
print(photo.name)
print("TableView2Finished")
return cell
}
推荐答案
您需要引用FirstViewController的实例,而不是实际的类定义.
You need to refer to the instance of the FirstViewController, not the actual class definition.
代替此:
if(FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage != nil) {
cell.imageView?.image = FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage
}
尝试一下:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstViewController = storyboard.instantiateViewController(withIdentifier: "FirstViewController") as! FirstViewController
if(firstViewController.defaults.data(forKey: photo.name + "image") as UIImage != nil) {
cell.imageView?.image = firstViewController.defaults.data(forKey: photo.name + "image") as UIImage
}
请确保为您的FirstViewController设置了 Storyboard标识符
,以便您可以通过代码中的标识符对其进行引用.
Make sure you set a Storyboard Identifier
for your FirstViewController so that you can reference it by the identifier in code.
编辑#1:
或者,您可以将字符串名称保存到 UserDefaults
并以这种方式访问.
Alternatively, you can save the string name to UserDefaults
and access it that way.
在您的第一个视图控制器中:
In your first view controller:
let defaults = UserDefaults.standard
defaults.set(photo.name, forKey: "FirstImage")
在表格视图控制器中:
let defaults = UserDefaults.standard
if let myImage = defaults.object(forKey: "FirstImage") as? String {
cell.imageView?.image = UIImage(named: myImage!)
}
这篇关于"UIViewController"不是"ViewController"的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!