问题
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
}
回答1:
You need to refer to the instance of the FirstViewController, not the actual class definition.
Instead of this:
if(FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage != nil) {
cell.imageView?.image = FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage
}
Try this:
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
}
Make sure you set a Storyboard Identifier
for your FirstViewController so that you can reference it by the identifier in code.
EDIT #1:
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")
In your table view controller:
let defaults = UserDefaults.standard
if let myImage = defaults.object(forKey: "FirstImage") as? String {
cell.imageView?.image = UIImage(named: myImage!)
}
来源:https://stackoverflow.com/questions/42214461/uiviewcontroller-is-not-a-subtype-of-viewcontroller