关于Swift3 中在viewController下的tableView无法显示数据的问题

相信很多人在用swift3中在viewController下使用tableView碰到很多的坑,本人也是在无数的测试下才找到解决方法的,废话不多说,进入正题:

首先检查是否继承了UITableViewDelegate和UITableViewDataSource,如下

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

override func viewDidLoad() {

super.viewDidLoad()

}

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

<#code#>

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

<#code#>

}

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

其次在viewDidLoad方法中设置代理和数据源方法

override func viewDidLoad() {

super.viewDidLoad()

let _tableView=UITableView(frame: UIScreen.main.bounds);

_tableView.delegate=self

_tableView.dataSource=self

}

其次其相应的内置方法也给有,如:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

func numberOfSections(in tableView: UITableView) -> Int

最后别忘了加入view的视图

self.view.addSubview(_tableView)

如果还是不行,请加入这行注册你的cell

_tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: cellID)

最后是完整代码

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

var dataArr = NSMutableArray()

let _tableView = UITableView()

var s = ["111","222","333"];

let cellID="myCell"

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

return s.count

}

func numberOfSections(in tableView: UITableView) -> Int {

return 1

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

var cell = tableView.dequeueReusableCell(withIdentifier: cellID);

if(cell == nil){

cell = UITableViewCell(style: .default, reuseIdentifier: cellID)

}

let t = s[indexPath.row]

cell!.textLabel?.text=t

return cell!

}

override func viewDidLoad() {

super.viewDidLoad()

_tableView.frame=UIScreen.main.bounds

_tableView.delegate=self

_tableView.dataSource=self

_tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: cellID)

self.view.addSubview(_tableView)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容