您的位置:首页 > 移动开发 > Swift

Swift学习记录 -- 15.tableView的创建与基本操作

2016-10-03 20:38 567 查看
算是正式接触到真正的东西了吧 , 大概写了下 , 不是太习惯 , 虽然有了extension , 和// MARK:- 分类注释 , 懒加载也不是太习惯 . 可能是OC敲太多了 , 还不是太适应吧 .

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{

//懒加载
let tableView:UITableView = {

let tableView = UITableView()
tableView.rowHeight = 100
tableView.estimatedRowHeight = 100

tableView.separatorColor = UIColor.redColor()

return tableView
}()

override func viewDidLoad() {
super.viewDidLoad()

initUI()
}
}


// extension + 类名  扩展,将方法抽出封装 (跟OC分类有点像,只能扩充方法,不能扩充属性)

// MARK:- 初始化UI
extension ViewController {

func initUI() {

//设置frame
tableView.frame = view.bounds
//设置数据源
tableView.dataSource = self
//设置代理
tableView.delegate = self
//添加到view上
view.addSubview(tableView)

}
}


// MARK:- 代理方法
extension ViewController{

//代理方法
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("当前选中行 - \(indexPath.row)")
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {

}
}


// MARK:- 数据源方法
extension ViewController{

//数据源方法
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cellID = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID)
if cell == nil {

//枚举的使用 : 1.枚举类型 + '.' + 具体类型 2.'.'+具体类型
//            cell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier: cellID)
cell = UITableViewCell(style: .Default, reuseIdentifier: cellID)
}

cell?.textLabel?.text = "嘿嘿嘿-\(indexPath.row)"

return cell!
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息