为什么故事板Uaithitview不显示

发布于 2025-01-23 13:09:01 字数 1879 浏览 2 评论 0原文

我是斯威夫特的新手。这是我对UI开发的第一个任务。我已经完美地完成了练习,表观视图如预期的那样出现。该代码如下:

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
    }
}

但是,当我遵循同一步骤并尝试将其与我的项目(带有导航控制器)集成在一起时,表视图不会显示。我想念什么吗?

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
    }
    
}

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
    }
    
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

俏︾媚 2025-01-30 13:09:01

我认为您必须在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")
}

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")
}
无语# 2025-01-30 13:09:01

在与Swift中的TableView合作时要记住的要点。

  • 确保桌面的约束得到正确给出。
  • 您已经将类连接到身份检查员中的视图控制器。
  • 在ViewDidload()本身中提供代表和数据源,而不是情节板以进行更好的练习。
  • 如果要为单元格创建XIB,请确保已注册了TableView的单元格,或者提供原型单元格,请确保提供Dequeuereusablecell()方法并初始化某些特定类别的单元格。

带有某些原型单元格的表图的简单示例

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文