Swift-UITableView拖動排序

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
   }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容