1 创建工程:打开xcode 选择ios平台下的sing view application ,选择swift语言,创建工程
2 在ViewController里面的添加代码
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
var tableView:UITableView?
var dataArr = NSMutableArray();
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor=UIColor.blueColor()
//初始化数据源
for i in 0...99{
dataArr.addObject("这是第\(i)行")
}
//定义表视图
let rect:CGRect=self.view.bounds//取得self.view的大小
tableView=UITableView(frame: rect,style: .Plain)
tableView!.dataSource=self
tableView!.delegate=self
self.view.addSubview(tableView!)
}
//实现dataSource协议 多行
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return dataArr.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cellID="my cell is "
var cell = tableView.dequeueReusableCellWithIdentifier(cellID)
if(cell == nil){
cell = UITableViewCell(style: .Default, reuseIdentifier: cellID)
}
let s = dataArr.objectAtIndex(indexPath.row) as! String
cell!.textLabel?.text=s
return cell!
}
//实现Delegate协议 点击事件
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
print("\(indexPath)行被点击了")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
3 实验结果