倒腾一天的tableView
首先是两种方式创建tableView,控件拖拽和代码生成。
然后最开始我想做的是页面跳转进入到一个tableView,并且不使用Navigation。
目前实现必须依托于storyboard,将主页和tableView都分别与stroryboard中的scene进行绑定,但是不使用拖拽控件。
在代码中生成TableView
并且需要实现UITableViewDelegate,UITableViewDataSource。
其中datasource中必须实现
1.func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{}
2.func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{}
每个点击时的cell的计数应该是indexPath.row()
代码备案:
class SecondViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
var table: UITableView?
var datas: NSString[] = []
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
initViews()
loadData()
}
func initViews(){
table = UITableView(frame: self.view!.frame)
self.table!.delegate = self
self.table!.dataSource = self
self.table!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view?.addSubview(self.table)
}
func loadData(){
for i in 1..10{
datas.append("str \(i)")
}
self.table!.reloadData()
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
return self.datas.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
var cell = table!.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text = self.datas[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
var i = indexPath.row
var alert = UIAlertView()
alert.title = "cell \(i)"
alert.delegate = self
alert.addButtonWithTitle("ok")
alert.message = "you select \(datas[i])"
alert.show()
// self.dismissViewControllerAnimated(true, completion: nil)
}
}