標籤:
UItableView實現移動儲存格
1,下面的範例是給表格UITableView添加儲存格移動功能:
- (1)給表格添加長按功能,長按後表格進入編輯狀態
- (2)在編輯狀態下,可以看到儲存格後面出現拖動按鈕
- (3)滑鼠按住拖動按鈕,可以拖動儲存格到任意位置
- (4)拖動完畢後,還會觸發TabelView對應的代理事件
2,如下: 3,代碼如下
1 import UIKit 2 3 class ViewController: UIViewController,UITableViewDelegate, 4 UITableViewDataSource,UIGestureRecognizerDelegate { 5 6 var tableView:UITableView? 7 8 var ctrlnames:[String] = ["UILabel 標籤","UIButton 按鈕","UIDatePiker 日期選取器", 9 "UITableView 表格視圖"]10 11 override func viewDidLoad() {12 super.viewDidLoad()13 14 //建立表視圖15 self.tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame,16 style:UITableViewStyle.Plain)17 self.tableView!.delegate = self18 self.tableView!.dataSource = self19 //建立一個重用的儲存格20 self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "SwiftCell")21 self.view.addSubview(self.tableView!)22 23 //綁定對長按的響應24 var longPress = UILongPressGestureRecognizer(target:self,25 action:Selector("tableviewCellLongPressed:"))26 //代理27 longPress.delegate = self28 longPress.minimumPressDuration = 1.029 //將長按手勢添加到需要實現長按操作的視圖裡30 self.tableView!.addGestureRecognizer(longPress)31 }32 33 //在本例中,只有一個分區34 func numberOfSectionsInTableView(tableView: UITableView!) -> Int {35 return 1;36 }37 38 //返回表格行數(也就是返回控制項數)39 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {40 return self.ctrlnames.count41 }42 43 //建立各單元顯示內容(建立參數indexPath指定的單元)44 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)45 -> UITableViewCell46 {47 //為了提供表格顯示效能,已建立完成的單元需重複使用48 let identify:String = "SwiftCell"49 //同一形式的儲存格重複使用,在聲明時登入50 let cell = tableView.dequeueReusableCellWithIdentifier(identify, forIndexPath: indexPath)51 as UITableViewCell52 cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator53 cell.textLabel?.text = self.ctrlnames[indexPath.row]54 return cell55 }56 57 //長按表格58 func tableviewCellLongPressed(gestureRecognizer:UILongPressGestureRecognizer)59 {60 if (gestureRecognizer.state == UIGestureRecognizerState.Ended)61 {62 println("UIGestureRecognizerStateEnded");63 //在正常狀態和編輯狀態之間切換64 if(self.tableView!.editing == false){65 self.tableView!.setEditing(true, animated:true)66 }67 else{68 self.tableView!.setEditing(false, animated:true)69 }70 }71 }72 73 //在編輯狀態,可以拖動設定cell位置74 func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {75 return true76 }77 78 //移動cell事件79 func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath,80 toIndexPath: NSIndexPath) {81 if fromIndexPath != toIndexPath{82 //擷取移動行對應的值83 var itemValue:String = ctrlnames[fromIndexPath.row]84 //刪除移動的值85 ctrlnames.removeAtIndex(fromIndexPath.row)86 //如果移動地區大於現有行數,直接在最後添加移動的值87 if toIndexPath.row > ctrlnames.count{88 ctrlnames.append(itemValue)89 }else{90 //沒有超過最大行數,則在目標位置添加剛才刪除的值91 ctrlnames.insert(itemValue, atIndex:toIndexPath.row)92 }93 }94 }95 }
iOS開發——UI_swift篇&UItableView實現移動儲存格