无法调用表视图委托和数据源方法



我设计了一个tableView,并以编程方式tableViewCell,不使用故事板。我在ViewController中的viewDidLoad()看起来像这样:

tableView.delegate = self
tableView.dataSource = self
tableView.register(TicketsTableViewCell.self,forCellReuseIdentifier:cellReuseIdentifier)
tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
self.view.addSubview(tableView)

我的tableViewCell看起来像这样:

class TicketsTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
//Other View related stuff
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}

问题是,当我运行它时,我能够看到tableView,但看不到单元格。此外,当我在cellForRowAt:处添加断点时,它不会被调用。我做错了什么?我在重用标识符方面有问题吗? 提前谢谢。

问题是首先您设置了delegatedatasourcetableView,然后使用第tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)行重新初始化tableView,因此先放置该行,然后设置delegatedatasource并注册单元格。

tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.register(TicketsTableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
self.view.addSubview(tableView)

像这样尝试可能会对您有所帮助

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
var tableView : UITableView!

override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.setUpTableView()
}
func setUpTableView()
{
// Create only one table view.
tableView = UITableView(frame: CGRectMake(self.view.frame.size.width / 10, self.view.frame.size.height / 2, self.view.frame.size.width - self.view.frame.size.width / 5, self.view.frame.size.height / 2 - 20), style: UITableViewStyle.Grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.layer.cornerRadius = 10
tableView.layer.borderColor = UIColor.blackColor().CGColor
tableView.layer.borderWidth = 2
self.view.addSubview(tableView)
}
//table view data source
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = "test"
cell.textLabel?.numberOfLines = 0
return cell
}
}

最新更新