TableView
TableView用来处理大量的数据,有以下两种方式:
一个典型的TableView由以下部分组成:
一个Table中的cell系统提供了以下四种方式:
准备工作
首先需要把storyboard清理干净,然后拖出新的tableviewcontroller。然后新建自己的TableViewController。
然后我们需要使用Twitter的framework,使用方法是把framework(工程文件)拖入项目内,但是要注意结构层次。
然后要把framework拖进去fakeTwitter的Embedded Binaries。不过可能会发现,这个framework一开始是红色的。使用之前需要使用Generic IOS Device来build一下。
然后再在使用framework的文件之前声明”import XX(framework name)”。
关键的三个函数
关于tableview最关键是如下三个函数。
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return newstitle.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Tweet", for: indexPath)
cell.textLabel?.text = newstitle[indexPath.row]
cell.detailTextLabel?.text = content[indexPath.row]
// Configure the cell...
return cell
}
其中里面要遍历多个元素的时候,使用indexPath.row。
但是样子还是很丑,可以使用自定义的方式来美化cell。
我们新建一个UITableViewCell文件,这个文件用来给我们创建所有View的部分。
我们需要在Storyboard里面拖好控件。然后把原本的代码改成如下的样子。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Tweet", for: indexPath)
// Configure the cell...
if let tweetCell = cell as? NewsTableViewCell {
tweetCell.title = newstitle[indexPath.row]
tweetCell.content = content[indexPath.row]
tweetCell.date = newsdate[indexPath.row]
}
return cell
}
NewTableViewCell做的事情只需要更新UI就可以了。