UITableView默认提供的提供拖动排序对于数据量比较多的时候是非常有效的,之前简单的写了一篇Swift关于中UITableView的简单使用,先来看一下UITableView的拖动排序效果图:
初始化数据
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.jianshu.com/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方法,如果不设置缩进,会距离左方有缩进,留下空白,按钮点击之后需要设置UITableView的编辑状态:
@IBAction func tableViewSortAction(sender: UIButton) {
print("Sort--FlyElephant")
let isEditing:Bool = !(self.tableView?.editing)!
self.tableView?.editing=isEditing
}