UITableView 不显示数据,但已经显示数据源和委托



我正在尝试制作一个显示一组数据的tableView(在viewController中)(我以前做过),但这次它没有显示数据。我已经将视图控制器声明为表视图的数据源和委托。这是我的viewControllerClass:

class MenuViewController: UIViewController , UITableViewDataSource ,          UITableViewDelegate {
    var menuItems = [ "1" , "2" , "3"]
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return menuItems.count
    }
    open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = menuItems[indexPath.row]
        return cell
    }
}

请检查您是否正在使用xib/Storyboard创建UITableView,然后数据源和代理插座已连接。否则,如果您以编程方式创建它,则设置委托和数据源。

你应该像这样在 viewDidLoad() 中注册单元格:

tableView.register(UITableViewCell.self, reuseIdentifier: "cell").希望这有帮助

你需要IBOutlet来表示你的tableView。在情节提要中,您需要从表视图拖放到菜单视图控制器。然后在您的 viewDidLoad 中,您需要设置数据源和委托。

override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
    }

现在,您的表视图不知道谁将提供数据。由于该数字OfRowsInSection和cellForRow不被调用。由于它们没有被调用,表视图不知道要显示什么。由于表视图不知道要显示什么,因此它不会显示任何内容。

最新更新