Swift UITableView的基本用法

var tableview = UITableView()

//    创建可变数组

var datas: NSMutableArray = ["1","2","3","4","5","6","7","8"]

override func viewDidLoad() {

super.viewDidLoad()

self.title = "UITableView"

//        设置tableView的宽高

tableview = UITableView(frame: CGRectMake(0, 0, view.frame.size.width, view.frame.size.height),style:UITableViewStyle.Plain)

//        设置代理

tableview.dataSource = self

//        设置数据源

tableview.delegate = self

self.view.addSubview(tableview)

}

//  代理方法tableView的行数

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

//    返回数组个数

return datas.count

}

//cell的独复用机制

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

let iden: String = "cell"

var cell = tableview.dequeueReusableCellWithIdentifier(iden)

if (cell == nil) {

cell = UITableViewCell(style: UITableViewCellStyle.Value1,reuseIdentifier: iden)

}

cell?.textLabel?.text = self.datas[indexPath.row] as? String

return cell!

}

//    设置cell的高度

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{

return 80

}

//    左滑动的时候自定义两个按钮

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

//        删除cell

let deleteAct : UITableViewRowAction = UITableViewRowAction(style: .Default,title: "删除"){(UITableViewRowAction,NSIndexPath)in

print("删除")

self.datas.removeObjectAtIndex(NSIndexPath.row)

tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)//平滑效果

//            刷线表单

tableView.reloadData()

}

let likeAct : UITableViewRowAction = UITableViewRowAction(style: .Normal,title: "喜欢"){ (UITableViewRowAction, NSIndexPath) in

print("喜欢")

}

return [deleteAct,likeAct]

}

你可能感兴趣的:(Swift UITableView的基本用法)