'UIViewController' is not a subtype of 'ViewController'

一世执手 提交于 2019-12-24 09:16:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!