相信很多人在用swift3中在viewController下使用tableView碰到很多的坑牙甫,本人也是在無(wú)數(shù)的測(cè)試下才找到解決方法的犁跪,廢話不多說(shuō)杨帽,進(jìn)入正題:
首先檢查是否繼承了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方法中設(shè)置代理和數(shù)據(jù)源方法
override func viewDidLoad() {
super.viewDidLoad()
let _tableView=UITableView(frame: UIScreen.main.bounds);
_tableView.delegate=self
_tableView.dataSource=self
}
其次其相應(yīng)的內(nèi)置方法也給有悠反,如:
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)
如果還是不行,請(qǐng)加入這行注冊(cè)你的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.
}
}