func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "reusedCell"
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if (cell == nil)
{
cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
}
let rowNum = (indexPath as NSIndexPath).row
//获取当前单元格,在段落中的行数
cell?.textLabel?.text = months[rowNum]
//根据单元格的行数,从数组中获取对应位置的元素,作为当前单元格的标题文字。
return cell!
}
override func viewDidLoad() {
super.viewDidLoad()
let rect = CGRect(x: 0, y: 140, width: 320, height: 420)
let tableView = UITableView(frame: rect)
tableView.dataSource = self
tableView.delegate = self
//初始化一个索引路径对象,用来表示表格中的第一个段落和第十二行的位置
let indexpath = IndexPath(row: 11, section: 0)
//调用表格对象的滚动到指定位置的方法,滑动到指定的索引位置
tableView.scrollToRow(at: indexpath, at: .top, animated: true)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "reusedCell"
//创建一个字符串,作为单元格的复用标识符,并从所有已经开辟内存的单元格里面,选择一个具有同样标识符的,空闲的单元格。
var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
if (cell == nil)
//如果在可重用使用的单元格队列中,没有可以重复使用的新的单元格,则创建新的单元格。新的单元格具有系统默认的单元格样式,并拥有一个复用标识符。
{
cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
}
let rowNum = (indexPath as NSIndexPath).row
//获取当前单元格,在段落中的行数
cell?.textLabel?.text = "cell Item \(rowNum)\(months[rowNum])"
//根据单元格的行数,从数组中获取对应位置的元素,作为当前单元格的标题文字。
if (rowNum % 2 == 0)
{
cell?.backgroundColor = UIColor.purple
}
else
{
cell?.backgroundColor = UIColor.orange
}
return cell!
}
标识符部分是重点
运行效果