Невозможно преобразовать возвращаемое выражение типа ForumViewController в ошибку типа UITableViewCell в XCODE - PullRequest
1 голос
/ 10 июля 2020

Мой код:

//
//  ForumViewController.swift
//  Kode4Kids
//
//  Created by Caleb Clegg on 17/06/2020.
//  Copyright © 2020 Group9. All rights reserved.
//

    import UIKit

    class ForumViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {
    
    class PostTableViewCell: UITableView{
        
        @IBOutlet weak var usernameLabel: UILabel!
        @IBOutlet weak var profileImageView: UIImageView!
        @IBOutlet weak var subtitleLabel: UILabel!
        @IBOutlet weak var postTextLabel: UILabel!
        
        override func awakeFromNib() {
            super.awakeFromNib()
            //initialization stuff
        }
        
        func set(post:Post) {
            usernameLabel.text = post.author
            postTextLabel.text = post.text
        }
        
}
    
    
    var tableView: UITableView!
    
    var posts = [
        
        Post(id: "1", author: "Ryan Johnston", text: "Kode4Kids Just Launched!"),
        Post(id: "2", author: "Caleb Clegg", text: "Woah This Is Lit!!"),
        Post(id: "3", author: "Habib Yusuf", text: "I LOVE THIS APP!"),
        Post(id: "4", author: "Maggie Mogul", text: "Gonna learn some HTML"),
        Post(id: "5", author: "Anthony Smith", text: "Just finished learning Python!"),
        Post(id: "6", author: "Renee Miseer", text: "So excited to start learning!"),
        Post(id: "7", author: "Alicia Keys", text: "Gonna stop singing to pick up code!"),
        Post(id: "8", author: "Dwayne Johnson", text: "Ah great craic"),
        Post(id: "9", author: "My dad", text: "okay"),
        Post(id: "10", author: "Kaiser Chief", text: "Sweeet app!"),
        Post(id: "12", author: "Darryl Granberry", text: "RUN IT UPP"),
        Post(id: "13", author: "Future", text: "Big racks on this app!")
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView.backgroundColor = UIColor.white
        let cellNib = UINib(nibName: "ForumViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "ForumCell")
        view.addSubview(tableView)
        
        var layoutGuide:UILayoutGuide!
        
        if #available(iOS 11.0, *){
        layoutGuide = view.safeAreaLayoutGuide
        } else {
            //fallback on previous versions
            layoutGuide = view.layoutMarginsGuide
        }
        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.reloadData()
    }
    
    
    
    
    @IBAction func backTapped(_ sender: Any) {
        
        let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController
                       
                       self.view.window?.rootViewController = homeViewController
                       self.view.window?.makeKeyAndVisible()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ForumCell", for: indexPath) as! ForumViewController
        return cell
        cell.set(post: posts[indexPath.row])
        
    }

}

Борьба с этой ошибкой, которая появляется в части cellForRow. Не совсем уверен, что мне нужно изменить. Буду признателен за любую помощь. На этом рисунке показана ошибка, ошибки не было, пока я не ввел "" ForumCell "для: indexPath) как! ForumViewController". Я не понимаю, почему отображается ошибка

Ответы [ 2 ]

0 голосов
/ 10 июля 2020

Эта строка: let cell = tableView.dequeueReusableCell(withIdentifier: "ForumCell", for: indexPath) as! ForumViewController используется для удаления из очереди UITableViewCell или подкласса UITableViewCell. Вы пытаетесь заставить его быть ForumViewController, что никогда не может работать.

Если вы создали собственный класс ячеек, используйте его. По крайней мере, это должно быть что-то вроде: let cell = tableView.dequeueReusableCell(withIdentifier: "ForumCell", for: indexPath) as! PostTableViewCell

0 голосов
/ 10 июля 2020

Необходимо указать ячейку вместо контроллера

     // it should be UITableViewCell instead of UITableView
    
    class PostTableViewCell: UITableViewCell {
        
        @IBOutlet weak var usernameLabel: UILabel!
        @IBOutlet weak var profileImageView: UIImageView!
        @IBOutlet weak var subtitleLabel: UILabel!
        @IBOutlet weak var postTextLabel: UILabel!
        
        override func awakeFromNib() {
            super.awakeFromNib()
            //initialization stuff
        }
        
        func set(post:Post) {
            usernameLabel.text = post.author
            postTextLabel.text = post.text
        }
        
    }


class ForumViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {   
    
    var tableView: UITableView!
    
    var posts = [
        
        Post(id: "1", author: "Ryan Johnston", text: "Kode4Kids Just Launched!"),
        Post(id: "2", author: "Caleb Clegg", text: "Woah This Is Lit!!"),
        Post(id: "3", author: "Habib Yusuf", text: "I LOVE THIS APP!"),
        Post(id: "4", author: "Maggie Mogul", text: "Gonna learn some HTML"),
        Post(id: "5", author: "Anthony Smith", text: "Just finished learning Python!"),
        Post(id: "6", author: "Renee Miseer", text: "So excited to start learning!"),
        Post(id: "7", author: "Alicia Keys", text: "Gonna stop singing to pick up code!"),
        Post(id: "8", author: "Dwayne Johnson", text: "Ah great craic"),
        Post(id: "9", author: "My dad", text: "okay"),
        Post(id: "10", author: "Kaiser Chief", text: "Sweeet app!"),
        Post(id: "12", author: "Darryl Granberry", text: "RUN IT UPP"),
        Post(id: "13", author: "Future", text: "Big racks on this app!")
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView = UITableView(frame: view.bounds, style: .plain)
        tableView.backgroundColor = UIColor.white
        let cellNib = UINib(nibName: "ForumViewCell", bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: "ForumCell")
        view.addSubview(tableView)
        
        var layoutGuide:UILayoutGuide!
        
        if #available(iOS 11.0, *){
        layoutGuide = view.safeAreaLayoutGuide
        } else {
            //fallback on previous versions
            layoutGuide = view.layoutMarginsGuide
        }
        tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.reloadData()
    }
    
    
    
    
    @IBAction func backTapped(_ sender: Any) {
        
        let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController
                       
                       self.view.window?.rootViewController = homeViewController
                       self.view.window?.makeKeyAndVisible()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return posts.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ForumCell", for: indexPath) as! PostTableViewCell
            return cell
            cell.set(post: posts[indexPath.row])
            
        }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...