UITableView默認提供的提供拖動排序?qū)τ跀?shù)據(jù)量比較多的時候是非常有效的,之前簡單的寫了一篇Swift關(guān)于中UITableView的簡單使用,先來看一下UITableView的拖動排序效果圖:

FlyElephant-Sort.gif
初始化數(shù)據(jù)
private func setup(){
self.view.backgroundColor = UIColor.whiteColor()
let tableFrame=CGRectMake(0, 120, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height-120)
self.tableView = UITableView.init(frame: tableFrame, style: UITableViewStyle.Plain)
self.tableView?.backgroundColor=UIColor.whiteColor()
self.tableView?.delegate=self
self.tableView?.dataSource=self
self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: CellIdentifier)
self.view.addSubview(self.tableView!)
self.data=["中山郎","FlyElephant","http://www.itdecent.cn/users/24da48b2ddb3/latest_articles","QQ群:228407086","keso","簡書","iOS","Swift"]
}
UITableViewDataSource&UITableViewDelegate
//MARK: UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let tableViewCell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier)
tableViewCell?.textLabel?.text="\(self.data[indexPath.row])"
return tableViewCell!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
//MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated:true)
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.None
}
func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let content=self.data[sourceIndexPath.row]
self.data.removeAtIndex(sourceIndexPath.row)
self.data.insert(content, atIndex: destinationIndexPath.row)
}
上面的方法中需要注意的是shouldIndentWhileEditingRowAtIndexPath方法,如果不設(shè)置縮進,會距離左方有縮進,留下空白,按鈕點擊之后需要設(shè)置UITableView的編輯狀態(tài):
@IBAction func tableViewSortAction(sender: UIButton) {
print("Sort--FlyElephant")
let isEditing:Bool = !(self.tableView?.editing)!
self.tableView?.editing=isEditing
}