TableView

1. TableView创建

2. 选中[Main.storyboard],删除右侧IB(Interface Builder)窗口中既有的[ViewController]

3. 从右侧控件窗口中,拖拽一个[TableViewController],进入IB中。并将此[TableViewController]设置为初使View。

step1:

step2:

step3:

4. 利用TableViewController中TableViewCell默认的风格进行设值。自带的TableViewCell中为我们提供了 textLabel,detailTextLabel,imageView三个项目来进行设值。

4.1 选中[Table View Cell],在右侧属性观察器中可以设定相应的[style]。

我们用[style]的[Basic]风格进行Cell的设定。

custom风格:

Basic风格:

RightDetail风格:

LeftDetail风格:

Subtitle风格:

4.2 在左侧的项目中,新建一个自定义的[CustomerTableViewContoller],并让其继承自[UITableViewController]。在该文件中重写两个实现方法。

1
2
3
4
5
6
7
// 有多少个子项(类似于Adapter里面的getCount())
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}

// 为每一个Row设置值(类似于Adapter里面的getView())
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}

4.3 选中[Table View Controller],设置[Identity观察器]中class选项设置为[CustomerTableViewContoller]。并且选中[Table View Cell],在右侧的属性窗口中,将[identity]属性设置 "Cell"

setp1:

setp2:

4.4 回到[CustomerTableViewContoller]类,为Cell进行设值。

4.5 至此,运行程序,可以看到下面的效果。

5. 自定义Cell,并且为Cell中的元素设置

5.1 制作自定义的Cell布局

step1: 选中IB中tableView,在右侧的尺寸观察器中,给属性[Row Height]设置相应的值。此处设置行高为: 80

step2: 先将[style]风格设置为[Custom],拖动一个StackView到Cell中,并添加StackView的约束为: 上:0, 左:0, 下:0

step3: 选中[Document Outline]中的[Stack View],右侧拖拽到[Cell]上,在弹出的窗口中,选择[Equal Widths]

step4: 选中[Document Outline]中的[Stack View],选择5个[Label]到StackView中,并设置相应的关联样式

step5: 我们想让第一个label固定宽度: 50, 第二个Label和第四个Label占比例为 2, 第三个Label和第五个Label占比例为 1

(1) 第一个Label设定:选中第一个Label,点击右下脚的[Add New Constraint],为该Label设置宽度:50

(2) 选中其余4个Label,添加约束: Equal Widths

结果:

(3) 选中第二个Label下面的等宽线,设置属性[Multiplier]的值为: 0.5

(4) 选中第五个Label下面的等宽线,设置属性[Multiplier]的值为: 0.5

(5) 至此,我们的布局就算完成了

5.2 上面的布局设置好,就是将Cell中的Label关联到自定义的Cell中