我正在使用一个标签栏 Controller ,我正试图从我的其他标签栏 View Controller 访问默认值。我在另一个功能中尝试了这个,如下所示,它工作得很好,但由于某种原因它在这里不起作用。每当调用它时它都会提出错误:FirstViewController().defaults
。有人知道为什么会这样吗?
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 的实例,而不是实际的类定义。
取而代之的是:
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 Identifier
,这样您就可以在代码中通过标识符引用它。
编辑#1:
或者,您可以将字符串名称保存到 UserDefaults
并以这种方式访问它。
在你的第一个 View Controller 中:
let defaults = UserDefaults.standard
defaults.set(photo.name, forKey: "FirstImage")
在你的 TableView Controller 中:
let defaults = UserDefaults.standard
if let myImage = defaults.object(forKey: "FirstImage") as? String {
cell.imageView?.image = UIImage(named: myImage!)
}
关于ios - 'UIViewController' 不是 'ViewController' 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42214461/