Home > front end >  why is storyboard UITableView not showing
why is storyboard UITableView not showing

Time:04-24

I am a novice to swift. This is my first assignment for UI development. I have done the exercise perfectly and the tableView showed up as expected. The code is as below:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView.delegate = self
        tableView.dataSource = self
    }


}

extension ViewController: UITableViewDelegate{
    
}

extension ViewController: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "gameScoreCell", for: indexPath)
        cell.textLabel?.text = "hello world"
        cell.detailTextLabel?.text = "score"
        return cell
    }
}

However, when I followed the same step and tried to integrate it with my project (with a navigation controller), the table view does not show up. Did I miss anything?

import UIKit

class HightScoreVC: UIViewController {

    @IBOutlet var rankingTable: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        rankingTable.delegate = self
        rankingTable.dataSource = self
    }


}

extension HightScoreVC: UITableViewDelegate{
    
}

extension HightScoreVC: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "gameScoreCell", for: indexPath)
        cell.textLabel?.text = "hello world"
        cell.detailTextLabel?.text = "123"
        return cell
    }
    
}

CodePudding user response:

I think you must register your cell in ViewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    rankingTable.delegate = self
    rankingTable.dataSource = self
    rankingTable.register(UITableViewCell.self, forCellReuseIdentifier: "gameScoreCell")
}

CodePudding user response:

Points to keep in mind while working with tableview in swift.

  • Make sure constriants of tableview are given properly.
  • You have connected the class to the view controller in the identity inspector.
  • Provide delegate and datasource in viewDidLoad() itself rather than storyboard for better practice.
  • If you are creating xib for a cell, make sure you have registered the cell for your tableview, or if you are providing prototype cell, make sure you provide dequeueReusableCell() method and initialize your cell for some specific class.

Simple example for a tableview with some prototype cell

import UIKit

class UsersListViewController: UIViewController, Storyboarded {

    //MARK: - Variables
    var coordinator: AuthenticationCoordinator?
    var usersList: UsersList?
    
    //MARK: - Outlets
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var progressBar: UIActivityIndicatorView!
    @IBOutlet weak var btnAddUser: UIButton!
    
    //MARK: - UIViewController
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeView()
        getUsersList()
    }
    
    //MARK: - Actions
    @IBAction func addUserAction(_ sender: UIButton) {
        coordinator?.presentAddUser()
    }
    
    //MARK: - File private functions
    fileprivate func initializeView() {
        self.title = "Users list"
        progressBar.startAnimating()
        btnAddUser.layer.masksToBounds = true
        btnAddUser.layer.cornerRadius = btnAddUser.frame.height / 2
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    fileprivate func getUsersList() {
        guard let url = URL(string: ApiUrl.delayResponseURL.rawValue) else { return }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        URLSession.shared.dataTask(with: request) { data, response, error in
            guard error == nil else { return }
            guard let data = data else { return }
            guard let response = response as? HTTPURLResponse, (200 ..< 299) ~= response.statusCode else { return }
            do {
                guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { return }
                guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else { return }
                guard let responseData = try? JSONDecoder().decode(UsersList.self, from: prettyJsonData) else { return }
                self.usersList = responseData
                DispatchQueue.main.async {
                    self.progressBar.stopAnimating()
                    self.progressBar.alpha = 0
                    self.tableView.reloadData()
                }
            } catch {
                return
            }
        }.resume()
    }
    
}//End of class

//MARK: - UITableViewDelegate
extension UsersListViewController: UITableViewDelegate {
   
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let index = usersList?.data[indexPath.row].userID {
            coordinator?.startSingleUserVC(index)
            tableView.deselectRow(at: indexPath, animated: true)
        }
    }
    
}//End of extension

//MARK: - UITableViewDataSource
extension UsersListViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "singleUserCell") as? SingleUserTableViewCell {
            if let url = URL(string: usersList?.data[indexPath.row].avatar ?? "") {
                DispatchQueue.global().async {
                    guard let data = try? Data(contentsOf: url) else { return }
                    val currentUser = self.usersList?.data[indexPath.row]
                    DispatchQueue.main.async {
                        cell.initCell(data, currentUser.firstName, currentUser.email)
                    }
                }
            }
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return usersList?.data.count ?? 1
    }
    
}//End of extension
  • Related