UITableVIew的简单实用
实现效果
//
// ViewController.swift
// DemoApp
//
// Created by 郭文亮 on 2018/11/15.
// Copyright 2018年 finalliang. All rights reserveds
//
import UIKit
//添加两个代理协议 表格视图的数据源协议 表格视图的代理协议
class ViewController: UIViewController ,UITableViewDelegate, UITableViewDataSource{
override func viewDidLoad() {
super.viewDidLoad();
let tableView = UITableView(frame: self.view.bounds)
//设置表格视图的代理为根视图控制器
tableView.delegate = self
//设置表格视图的资源代理为根视图控制器
tableView.dataSource = self
//初始化一个索引路径。第1个段落的第16行
let indexpath = IndexPath(row: 49, section:0)
//让表格滑动到指定位置
tableView.scrollToRow(at: indexpath, at: UITableViewScrollPosition.bottom, animated: true)
self.view.addSubview(tableView)
}
//代理方法。重写的。设置表格视图拥有单元格的行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
//代理方法。设置高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
//初始化或复用表格中的单元格
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let indetifier = "reusedCell"
//单元格的标识符。可以看作是一种复用机制。 此方法可以从已开辟内存的单元格里面选择一个具有同样标识的空闲的单元格
var cell = tableView.dequeueReusableCell(withIdentifier: indetifier)
//判断在可重用单元格队列中,是否有可以重复使用的单元格
if (cell==nil) {
//如果没有可以重复使用的单元格,则创建新的单元格。
//新的单元格具有i 系统默认的样式,并拥有一个复用标识符
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: indetifier)
}
//索引路径用来标示单元格在表格中的位置 段落section 行数row
let rowNum = (indexPath as NSIndexPath).row
//默认的单元格,拥有一个标签对象 对象的文字内容
cell?.textLabel?.text = "第\(rowNum)个"
//设置标签的描述内容
cell?.detailTextLabel?.text = "Detail information here"
cell?.imageView?.image=UIImage(named: "Tab")
cell?.imageView?.highlightedImage = UIImage(named: "Tab2")
//设置背景色的两种方式
if (rowNum==3) {
cell?.backgroundColor=UIColor.red
}else{
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.backgroundColor=UIColor.blue
cell?.backgroundView=view
}
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//
// ViewControl