相信很多人在用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.
}
}