今天在簡(jiǎn)書(shū)上看到一個(gè)類(lèi)似的文章律杠,用的是oc方式實(shí)現(xiàn)话侧,然后自己無(wú)聊用Swift方法實(shí)現(xiàn)下灸芳,也算是練習(xí)一下期升。
代碼如下
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
var tableview:UITableView = UITableView();//建立tableview
var dataArr:NSMutableArray = [1,2,3,4,5,6,7,8];//設(shè)置數(shù)據(jù)源
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableview.bounds = UIScreen.mainScreen().bounds;//設(shè)置tablview的大小
tableview.center = CGPointMake(UIScreen.mainScreen().bounds.maxX/2, UIScreen.mainScreen().bounds.maxY/2)//設(shè)置tableview的中心
tableview.backgroundColor = UIColor.whiteColor();
tableview.delegate=self;
tableview.dataSource=self;
self.view.addSubview(tableview);
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let Idnetfier = "cell"
let cell:UITableViewCell = UITableViewCell(style: .Default, reuseIdentifier: Idnetfier)
cell.textLabel?.text = "\(dataArr[indexPath.row])I am a cell";
return cell;
}
//設(shè)置動(dòng)作按鈕的函數(shù)
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
//添加刪除按鈕
let deleteRowAction:UITableViewRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "刪除", handler: {
(action:UITableViewRowAction,index:NSIndexPath) in
//先從數(shù)據(jù)源那里刪除數(shù)據(jù)
self.dataArr.removeObjectAtIndex(indexPath.row);
//然后在把tableview上的指定行刪除
self.tableview.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic);
})
let insertRowAction:UITableViewRowAction = UITableViewRowAction(style:.Default, title: "置頂", handler: {
(action:UITableViewRowAction,index:NSIndexPath) in
//把數(shù)據(jù)源地一行的數(shù)據(jù)和當(dāng)前點(diǎn)擊行的數(shù)據(jù)交換
self.dataArr.exchangeObjectAtIndex(0, withObjectAtIndex: indexPath.row);
//獲取tableview中第一行的indexpath
let firstIndex:NSIndexPath = NSIndexPath(forRow: 0, inSection: indexPath.section)
//通過(guò)第一行的index和當(dāng)前點(diǎn)擊行的index來(lái)進(jìn)行行的交換
self.tableview.moveRowAtIndexPath(indexPath, toIndexPath: firstIndex);
})
let moreRowAction:UITableViewRowAction = UITableViewRowAction(style:.Default, title: "重置", handler: {
(action:UITableViewRowAction,index:NSIndexPath) in
//重新加載tablview
self.tableview.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Bottom)
})
let actions = [deleteRowAction,insertRowAction,moreRowAction];
return actions;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}