目錄:[Swift]Xcode實際操做html
本文將演示如何刪除某一行單元格。手勢左滑調出刪除按鈕。swift
在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】數組
1 import UIKit 2 3 //首先添加兩個協議。 4 //一個是表格視圖的代理協議UITableViewDelegate 5 //另外一個是表格視圖的數據源協議UITableViewDataSource 6 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 7 8 //建立一個數組,做爲表格的數據來源 9 var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] 10 11 override func viewDidLoad() { 12 super.viewDidLoad() 13 // Do any additional setup after loading the view, typically from a nib. 14 15 //建立一個位置在(0,40),尺寸爲(320,420)的顯示區域 16 let rect = CGRect(x: 0, y: 40, width: 320, height: 420) 17 //初始化一個表格視圖,並設置其位置和尺寸信息 18 let tableView = UITableView(frame: rect) 19 20 //設置表格視圖的代理,爲當前的視圖控制器 21 tableView.delegate = self 22 //設置表格視圖的數據源,爲當前的視圖控制器 23 tableView.dataSource = self 24 25 //將表格視圖,添加到當前視圖控制器的根視圖中 26 self.view.addSubview(tableView) 27 } 28 29 //添加一個代理方法,用來設置表格視圖,擁有單元格的行數 30 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 31 //在此使用數組的長度,做爲表格的行數 32 return months.count 33 } 34 35 //添加一個代理方法,用來初始化或複用表格視圖中的單元格 36 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 37 38 //建立一個字符串,做爲單元格的複用標識符 39 let identifier = "reusedCell" 40 //單元格的標識符,能夠看做是一種複用機制。 41 //此方法能夠從,全部已經開闢內存的單元格里面,選擇一個具備一樣標識符的、空閒的單元格 42 var cell = tableView.dequeueReusableCell(withIdentifier: identifier) 43 44 //判斷在可重用單元格隊列中,是否擁有能夠重複使用的單元格。 45 if(cell == nil) 46 { 47 //若是在可重用單元格隊列中,沒有能夠重複使用的單元格, 48 //則建立新的單元格。新的單元格具備系統默認的單元格樣式,並擁有一個複用標識符。 49 cell = UITableViewCell(style: .default, reuseIdentifier: identifier) 50 } 51 52 //索引路徑用來標識單元格在表格中的位置。它有section和row兩個屬性, 53 //section:標識單元格處於第幾個段落 54 //row:標識單元格在段落中的第幾行 55 //獲取當前單元格的行數 56 let rowNum = (indexPath as NSIndexPath).row 57 //根據當前單元格的行數,從數組中獲取對應位置的元素,做爲當前單元格的標題文字 58 cell?.textLabel?.text = months[rowNum] 59 60 //返回設置好的單元格對象。 61 return cell! 62 } 63 64 //添加一個代理方法,用來設置單元格的編輯模式 65 func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { 66 //在此設置單元格的編輯模式爲刪除模式 67 return UITableViewCell.EditingStyle.delete 68 } 69 70 //添加一個代理方法,用來響應單元格的刪除事件 71 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { 72 //判斷若是執行模式爲刪除,則執行以後的代碼 73 if(editingStyle == UITableViewCell.EditingStyle.delete) 74 { 75 //獲取待刪除的單元格,在段落中的行數 76 let rowNum = (indexPath as NSIndexPath).row 77 //從數組中將該單元格清除,以保證數據的一致性 78 months.remove(at: rowNum) 79 80 //建立一個待刪除單元格位置信息的數組 81 let indexPaths = [indexPath] 82 //再從表格視圖中,清除該單元格 83 tableView.deleteRows(at: indexPaths, with: UITableView.RowAnimation.automatic) 84 } 85 } 86 87 override func didReceiveMemoryWarning() { 88 super.didReceiveMemoryWarning() 89 // Dispose of any resources that can be recreated. 90 } 91 }