1.传统类似OC中的写法
//
// ViewController.swift
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
override func loadView() {
let tableView = UITableView()
tableView.frame = UIScreen.mainScreen().bounds
tableView.dataSource = self
tableView.delegate = self
view = tableView
}
// MARK: - 懒加载数据
lazy var dataList:[String] = {
return ["jack","zhangsan","xiaoming","lisi","lily"]
}()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 1.创建cell
var cell = tableView.dequeueReusableCellWithIdentifier("cell")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.Default
, reuseIdentifier: "cell")
}
// 2.设置数据
cell?.textLabel?.text = dataList[indexPath.row]
return cell!
}
}
2.苹果官方推荐的更加优雅的写法
//
// ViewController.swift
import UIKit
class ViewController: UIViewController {
override func loadView() {
let tableView = UITableView()
tableView.frame = UIScreen.mainScreen().bounds
tableView.dataSource = self
tableView.delegate = self
view = tableView
}
// MARK: - 懒加载数据
lazy var dataList:[String] = {
return ["jack","zhangsan","xiaoming","lisi","lily"]
}()
override func viewDidLoad() {
super.viewDidLoad()
}
}
// 苹果官方建议,可以将数据代理方法单独写到一个扩展中,以便于代码的可读性
// extension 相当于OC的 category
extension ViewController:UITableViewDataSource,UITableViewDelegate{
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 1.创建cell
var cell = tableView.dequeueReusableCellWithIdentifier("cell")
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.Default
, reuseIdentifier: "cell")
}
// 2.设置数据
cell?.textLabel?.text = dataList[indexPath.row]
return cell!
}
}