
哈哈,是不是很想开发出像图片上面一样精美的apps啊?我也好想啊,可是我的水平还不够,只能慢慢来了,不积小流,何以致江海呢?
今天学习的是UITableView,这是apps中最基本的控件了。你手机里面的大部分应用,基本的结构都是由表格构成的。动手永远是最好的学习方法,我会写一个大概的操作过程,但是具体的细节我不会过多地去写,如果有疑问或者我做得有什么不对的地方,请多多指教。
新建一个project,Single View Application,先到Main.storyboard里设计UI界面,在右下角的控件库里拖一个Table View出来:

设置一样prototype cell的行数和类型,运行一下:

什么都没有对吧?嗯,目前来说它就应该是这个样子的,因为我们什么都没做啊,就是拖一个控件进去而已。
作为一个控件,它是什么都不知道的,也不知道要干嘛,这些也不是它的职责(MVC设计模式)。我们得告诉它要显示什么数据和要干什么。在Swift里,我们需要用到协议(protocol)
呃,要解释一下什么是协议吗?假设你要创业,你雇了一个设计师来为你的工司设计logo,但是他不能马上开始设计,他需要知道公司的名称,还有你喜欢的颜色之类的信息,但是你又很忙,没空理他,所以你把这些事情都交给你的助手。在iOS里面也是如此。table view需要知道一些基本的信息:
- 在表格里有多少行?
- 数据是什么?
我们通过协议来传递这些信息。
代码这样写:

还有一件事,就是要将控件和代码连接起来,通过Control-drag:

运行一下看看:

哈,有结果了吧,虽然现在还不是很好看,但是起码它可以显示数据了。
想把它做得好看点吧?那继续。
先看看完成后的样子:

对比之前那个,有了几个变化:
1,每一行的高度
2,有一个缩略图,而且是圆形的
3,展示了餐厅更多的信息
4,改变字体的大小
要做到上述几点,我们需要定制自己的表格。其实绝大多数工作都无需代码即可完成,基本上就是在Xcode里拖拖控件。
新建一个RestaurantCell.swift,将代码和控件连接起来:

把RestaurantTableViewController.swift里tableView方法改成:
let cell = tableView.dequeueReusableCellWithIdentifier(identifier) as! RestaurantCell

基本上快完成了,还差将缩略图变成圆形。
很简单,就两行代码的事情:
cell.thumbnailImageView.layer.cornerRadius = cell.thumbnailImageView.frame.size.width / 2 cell.thumbnailImageView.clipsToBounds = true
最后上个成品图:

今天的任务就到此结束了。
网友评论