本文将演示如何插入一行单元格。
在项目导航区,打开视图控制器的代码文件【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, 320, height: 420) 17 //初始化一个表格视图,并设置其位置和尺寸信息 18 let tableView = UITableView(frame: rect) 19 20 //设置表格视图的代理,为当前的视图控制器 21 tableView.delegate = self 22 //设置表格视图的数据源,为当前的视图控制器 23 tableView.dataSource = self 24 //在默认状态下,开启表格的编辑模式 25 tableView.setEditing(true, animated: false) 26 27 //将表格视图,添加到当前视图控制器的根视图中 28 self.view.addSubview(tableView) 29 } 30 31 //添加一个代理方法,用来设置表格视图,拥有单元格的行数 32 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 33 //在此使用数组的长度,作为表格的行数 34 return months.count 35 } 36 37 //添加一个代理方法,用来初始化或复用表格视图中的单元格 38 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 39 40 //创建一个字符串,作为单元格的复用标识符 41 let identifier = "reusedCell" 42 //单元格的标识符,可以看作是一种复用机制。 43 //此方法可以从,所有已经开辟内存的单元格里面,选择一个具有同样标识符的、空闲的单元格 44 var cell = tableView.dequeueReusableCell(withIdentifier: identifier) 45 46 //判断在可重用单元格队列中,是否拥有可以重复使用的单元格。 47 if(cell == nil) 48 { 49 //如果在可重用单元格队列中,没有可以重复使用的单元格, 50 //则创建新的单元格。新的单元格具有系统默认的单元格样式,并拥有一个复用标识符。 51 cell = UITableViewCell(style: .default, reuseIdentifier: identifier) 52 } 53 54 //索引路径用来标识单元格在表格中的位置。它有section和row两个属性, 55 //section:标识单元格处于第几个段落 56 //row:标识单元格在段落中的第几行 57 //获取当前单元格的行数 58 let rowNum = (indexPath as NSIndexPath).row 59 //根据当前单元格的行数,从数组中获取对应位置的元素,作为当前单元格的标题文字 60 cell?.textLabel?.text = months[rowNum] 61 62 //返回设置好的单元格对象。 63 return cell! 64 } 65 66 //添加一个代理方法,用来设置单元格的编辑模式 67 func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { 68 //在此设置单元格的编辑模式为插入模式 69 return UITableViewCell.EditingStyle.insert 70 } 71 72 //添加一个代理方法,用来响应单元格的插入事件 73 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { 74 //判断编辑模式为插入,则执行之后的代码 75 if(editingStyle == UITableViewCell.EditingStyle.insert) 76 { 77 //获取插入位置的单元格在段落中的行数 78 let rowNum = (indexPath as NSIndexPath).row 79 //往数组中插入新数据,及时更新数据源 80 months.insert("Honey Moon", at: rowNum) 81 82 //创建一个包含带插入单元格位置信息的数组 83 let indexPaths = [indexPath] 84 //往表格视图中的指定位置,插入新单元格 85 tableView.insertRows(at: indexPaths, with: UITableView.RowAnimation.right) 86 } 87 } 88 89 override func didReceiveMemoryWarning() { 90 super.didReceiveMemoryWarning() 91 // Dispose of any resources that can be recreated. 92 } 93 }