2017-06-18 70 views
1

我想在代码中用示例数据填充基本tableview。这里是我的ViewController:为什么我的tableView没有被填充?

import UIKit 

class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

    @IBOutlet weak var postTableView: UITableView! 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 4 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "postcell", for: indexPath) 

     cell.textLabel?.text = "title" 
     cell.detailTextLabel?.text = "detail" 
     return cell 
    } 
} 

这是我的故事板 enter image description here

我敢肯定,这个名字"postcell"是正确的,我已经迷上了的tableView到ViewController作为数据源和委托。

当我在iOS模拟器中运行代码时,没有显示出单元格。这是我所看到的:

enter image description here

这里是我的堆栈视图约束 enter image description here

堆叠视图属性

enter image description here enter image description here

我不希望使用UITableViewController

如何获取表格单元格?

+0

在你的故事板中,你有没有确保视图控制器的类是'TableViewController'? – TylerTheCompiler

+0

@MrSaturn是的,它是TableViewController –

+0

@MrSaturn我已经添加了我的故事板,这有帮助吗? –

回答

2

如果“postcell”是不是从你的故事板原型细胞,你需要在viewDidLoad中进行注册:

postTableView.register(UITableViewCell.self, forCellReuseIdentifier: "postcell") 

如果是厦门国际银行表视图细胞需要按如下方式来注册它

postTableView.register(UINib(nibName: "NibName", bundle: nil), forCellReuseIdentifier: "postcell") 

如果你从故事板做到这一点,将一个原型细胞(或表视图细胞)到你的表视图和再利用标识称之为“postcell”如下所示:

Prototype table view cell

确保你也做你的viewDidLoad以下几点:

postTableView.delegate = self 
    postTableView.dataSource = self 

当然,你还需要:

func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 
+2

'numberOfSections(in:)'不是必需的。如果你没有实现它,那么假定有一个部分。 – TylerTheCompiler

+0

有没有使单元格成为故事板中原型单元格的方法? –

+0

是的。只需将一个表格视图单元从对象库拖到表格视图中,并在重用标识符中将其称为“postcell” – gwinyai

1
中的tableView

(_的tableView:UITableView的,cellForRowAt indexPath:IndexPath)

let cell = tableView.dequeueReusableCell(withIdentifier:“postcell”,for:indexPath)as postcell // add this line

1

谢谢@MrSaturn在评论中指出这是堆栈视图的问题。在故事板中,我必须将堆栈视图的对齐属性从中心更改为填充。