ios - 'UIViewController' 不是 'ViewController' 的子类型

标签 ios iphone swift uitableview uiviewcontroller

我正在使用一个标签栏 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/

相关文章:

ios - 使用 swift 3 对自定义字典进行排序

ios - 如果一个强属性具有一个涉及 self 的障碍,那是一个保留周期吗?

iOS UIButton 点击​​不起作用

iphone - 获取TMXTiledMap的tileet文件名

ios - 在具有委托(delegate)的多个 UIViewController 队列上使用解雇 View Controller

ios - GCD NSURLSession completionHandler block 返回值 null

iphone - Xcode 4.6 调试 - 源代码未显示(方案和调试工作流程设置正确)

iphone - 我需要删除导致崩溃的 IBOUTLET 连接

swift - PBJVision 切换到前置摄像头

arrays - 如何转发带有可变参数的函数?