iOS Swift 动态给tableView插入行

TableView在一个项目中是必然会用到的, 如果没有TableView的话可以想象, 写界面是件多么痛苦的事, 好了废话不多说, 进入正题

新建一个Swift iOS 项目

老样子我们先新建一个single view application

参照这个就行了 http://huyaohui.com/2015/05/28/resignFirstResponder-close-keyboard/

新建一个Table View Controller

  • 把Main.storyboard中默认的ViewController删了

  • 从 object library中拖一个Table View Controller到storyboard中

  • 勾上 is Initial View Controller(不勾上就没有入口的View Controller了)

设置TableViewCell

选择TableViewCell

  • 设置Style属性为Custom(自定义模式)

  • Identifier取名为TableViewCell(代码部分需要用到)

控件Tag

给我们的TableViewCell中的Label(实际中可能是其他的, 同理)添加Tag标记

绑定Swift类

  • 新建一个TableViewController.swift 文件, 继承UITableViewController

  • 关联到上面新建的那个storyboard的TableViewController中

关键代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import UIKit
class TableViewController: UITableViewController {
// 虚拟数据, 实际情况可以是通过http从服务器上拿到的
let cacheData = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 告诉Tableview cell的行数
// 要不然系统也不知道你总共有多少行不是吗
return cacheData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 获取一个UITableViewCell对象
let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell") as! UITableViewCell
// 获取UITableViewCell中的控件
var labelName = cell.viewWithTag(100) as! UILabel
// 动态把值插入cell中
labelName.text = cacheData[indexPath.row]
return cell
}
}

代码地址

MakeHui/SwiftBaseCodes

总结

其实TableView的应用场景还不只是这些, 他还提供了很多方法, 给我们修改TableView的展现方式, 其实很灵活的, 我写的这个例子是最常见的, 不是那么常见的就要靠大家去摸索了, 总之大同小异