创建UITablView

import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{var Names = ["A","B","C","D","E","F"]var tableView:UITableView!override func viewDidLoad() {super.viewDidLoad()//创建表格图self.tableView = UITableView(frame: self.view.frame, style: .plain)//将代理,数据来源设为自己self.tableView?.delegate = selfself.tableView?.dataSource = self//创建表头标签let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 30))headerLabel.text = "Header"self.tableView?.tableHeaderView = headerLabelself.view.addSubview(tableView)}//设置分区数(不设置默认为1)func numberOfSections(in tableView: UITableView) -> Int {return 1}//设置单元格数func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return Names.count}//设置单元格内容func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {//设置重用单元格名称let identifier = "reusedCell"//使用重用单元格var cell = tableView.dequeueReusableCell(withIdentifier: identify)//如果单元格为nil创建重用单元格if cell == nil{cell = UITableViewCell(style: .default, reuseIdentifier: identify)}cell?.textLabel?.text = Names[indexPath.row]return cell!}//自定义单元格高度func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {return 40}//点击单元格响应时间func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {self.tableView?.deselectRow(at: indexPath, animated: true)//使被点击的单元格的颜色立即恢复let cell = tableView.cellForRow(at: indexPath)if cell?.accessoryType == UITableViewCell.AccessoryType.none{cell?.accessoryType = .checkmarkprint("你选择了:\(String(describing: cell?.textLabel?.text))")}else{cell?.accessoryType = .none}}}

使用不同样式单元格

import UIKitclass CustomizeTableViewCell: UITableViewCell {var UserImage:UIImageView!var UserName:UILabel!var Detail:UIButton!override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {super.init(style: style, reuseIdentifier: reuseIdentifier)self.UserImage = UIImageView(image: UIImage(named: "UserImage"))self.UserImage.center = CGPoint(x: 30, y: 22)self.UserName = UILabel(frame: CGRect(x: 80, y: 0, width: 120, height: 40))self.UserName.text = "自定义单元格"self.Detail = UIButton(frame: CGRect(x: 240, y: 8, width: 60, height: 24))self.Detail.setTitle("详情", for: .normal)self.Detail.backgroundColor = UIColor.grayself.Detail.addTarget(self, action: #selector(showDetail), for: .touchUpInside)self.addSubview(self.UserName)self.addSubview(self.UserImage)self.addSubview(self.Detail)}@objc func showDetail(){print("显示详情信息")}required init?(coder aDecoder: NSCoder) {fatalError("init(coder:) has not been implemented")}}

效果图:

自定义UItableViewCell

创建一个Cocoa Touch class文件,设置父类:UITableViewCell,名称为CustomizeTableViewCell

编辑CustomizeTableViewCell:

import UIKitclass CustomizeTableViewCell: UITableViewCell {var UserImage:UIImageView!var UserName:UILabel!var Detail:UIButton!override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {super.init(style: style, reuseIdentifier: reuseIdentifier)self.UserImage = UIImageView(image: UIImage(named: "UserImage"))self.UserImage.center = CGPoint(x: 30, y: 22)self.UserName = UILabel(frame: CGRect(x: 80, y: 0, width: 120, height: 40))self.UserName.text = "自定义单元格"self.Detail = UIButton(frame: CGRect(x: 240, y: 8, width: 60, height: 24))self.Detail.setTitle("详情", for: .normal)self.Detail.backgroundColor = UIColor.grayself.Detail.addTarget(self, action: #selector(showDetail), for: .touchUpInside)self.addSubview(self.UserName)self.addSubview(self.UserImage)self.addSubview(self.Detail)}@objc func showDetail(){print("显示详情信息")}required init?(coder aDecoder: NSCoder) {fatalError("init(coder:) has not been implemented")}}

编辑ViewController:

import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{var user = ["A","B","C"]override func viewDidLoad() {super.viewDidLoad()let tableView = UITableView(frame: self.view.frame)tableView.dataSource = selftableView.delegate = selfself.view.addSubview(tableView)}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return user.count}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let identifier = "reusedCell"var cell:CustomizeTableViewCell? = tableView.dequeueReusableCell(withIdentifier: identifier) as? CustomizeTableViewCellif cell == nil{cell = CustomizeTableViewCell(style: .default, reuseIdentifier: identifier)}cell?.UserName.text = user[indexPath.row]return cell!}}

给文章添加章节和索引

import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{var Section = ["A","B","C","D","E","F","G","H","I","G","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","z"]var Content =   [["1","2","3"],["3","4"],["5","6"],["7","8"],["9","10"],["11","12"],["13","14"],["15","16"],["12","21"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"]]var tableView:UITableView!override func viewDidLoad() {super.viewDidLoad()//创建表格图self.tableView = UITableView(frame: self.view.frame, style: .grouped)self.tableView?.delegate = selfself.tableView?.dataSource = self//创建表头标签let headerLabel = UILabel(frame: CGRect(x: self.view.bounds.width/2, y: 0, width: self.view.bounds.width, height: 30))headerLabel.text = "添加章节和索引"self.tableView?.tableHeaderView = headerLabelself.view.addSubview(tableView)print(Content.count)}//设置分区数(不设置默认为1)func numberOfSections(in tableView: UITableView) -> Int {return Section.count}//设置单元格数func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return Content[section].count}//设置单元格表头func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {return self.Section[section]}//设置单元格表尾func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {return "有\(self.Content[section].count)个控件"}//设置索引内容func sectionIndexTitles(for tableView: UITableView) -> [String]? {return self.Section}//设置单元格内容func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let identifier = "reusedCell"var cell = tableView.dequeueReusableCell(withIdentifier: identify)if cell == nil{cell = UITableViewCell(style: .default, reuseIdentifier: identify)}let section = indexPath.sectionvar data = self.Content[section]cell?.textLabel?.text = data[indexPath.row]return cell!}//点击单元格响应时间func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {self.tableView?.deselectRow(at: indexPath, animated: true)//使被点击的单元格的颜色立即恢复let section = indexPath.sectionvar data = self.Content[section]let alertController = UIAlertController(title: "提示", message: "你点击了:\(data[indexPath.row])", preferredStyle: .alert)let ok = UIAlertAction(title: "确定", style: .default, handler: nil)alertController.addAction(ok)present(alertController, animated: true, completion: nil)}}

单元格的删除,插入,移动

import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{var SectionNum = ["delete","insert","move"]var Content = [["A","B"],["C","D"],["E","F"]]var tableView:UITableView!override func viewDidLoad() {super.viewDidLoad()tableView = UITableView(frame: self.view.frame)tableView.dataSource = selftableView.delegate = self//设置是否为编辑模式tableView.setEditing(false, animated: true)self.view.addSubview(tableView)//添加一个手势来开启/关闭编辑模式let Tap = UITapGestureRecognizer(target: self, action: #selector(OpenEdit))Tap.numberOfTapsRequired = 2Tap.numberOfTouchesRequired = 1self.view.addGestureRecognizer(Tap)}@objc func OpenEdit(){if self.tableView.isEditing{tableView.setEditing(false, animated: true)}else{tableView.setEditing(true, animated: true)}}//设置区域数func numberOfSections(in tableView: UITableView) -> Int {return SectionNum.count}//设置行数func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {let data = Content[section]return data.count}//设置内容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 data = Content[indexPath.section]cell?.textLabel?.text = data[indexPath.row]return cell!}//设置章节名称func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {return SectionNum[section]}//设置编辑状态下显示的图标(none,insert,delete三种图案)func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {if indexPath.section == 0{return UITableViewCell.EditingStyle.delete}else if indexPath.section == 1{return UITableViewCell.EditingStyle.insert}return UITableViewCell.EditingStyle.none}//使用删除,插入执行此方法func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {if editingStyle == .delete{self.Content[indexPath.section].remove(at: indexPath.row) //删除选项,并设置删除的效果//更新表格数据self.tableView.reloadData()}else {self.Content[indexPath.section].insert("F", at: indexPath.row)self.tableView.reloadData()}}//修改删除提示的问题func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {return "X"}//设置单元格的位置可以拖动func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {if indexPath.section == 2{return true}return false}//移动完单元格调用此方法func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {print("你使用了此方法")let formRow = sourceIndexPath.rowlet toRow = destinationIndexPath.rowlet formContent = Content[formRow]Content.remove(at: formRow)Content.insert(formContent, at: toRow)}}

效果图:

TableViewCell嵌套

import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{var articles = ["A","B"]var Contents = ["1","2"]override func viewDidLoad() {super.viewDidLoad()let tableView = UITableView(frame:self.view.frame)tableView.delegate = selftableView.dataSource = selftableView.separatorStyle = .noneself.view.addSubview(tableView)}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return articles.count*2}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let idA = "articlesCell"let idB = "ContentsCell"var CellA:UITableViewCell?var CellB:UITableViewCell?if indexPath.row%2 == 0{CellA = tableView.dequeueReusableCell(withIdentifier: idA)if CellA == nil{CellA = UITableViewCell(style: .default, reuseIdentifier: idA)}CellA?.textLabel?.text = articles[indexPath.row/2]return CellA!}else{CellB = tableView.dequeueReusableCell(withIdentifier: idB)if CellB == nil{CellB = UITableViewCell(style: .default, reuseIdentifier: idB)}CellB?.textLabel?.text = Contents[indexPath.row/2]return CellB!}}}

嵌套自定义单元格

创建一个自定义swift文件,父类为UITableViewCell,名称为CustomizeTableVIewCell
编辑CustomizeTableViewCell:

import UIKitclass CustomizeTableViewCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate {var tableView:UITableView!var Content:[String] = []override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {super.init(style: style, reuseIdentifier: reuseIdentifier)//进行初始化,后续在进行更改tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 300, height: 50))tableView.dataSource = selftableView.delegate = self//设置是否允许滑动(设为false,防止内容跟着手指滑动而滑动)tableView.isScrollEnabled = falsetableView.separatorStyle = .noneself.addSubview(tableView)}//设置单元格数量func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return Content.count}//设置单元格内容func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let id = "reusedCell"var cell = tableView.dequeueReusableCell(withIdentifier: id)if cell == nil{cell = UITableViewCell(style: .default, reuseIdentifier: id)}cell?.textLabel?.text = Content[indexPath.row]cell?.textLabel?.font = UIFont.systemFont(ofSize: 12)cell?.textLabel?.numberOfLines = 0return cell!}//设置单元格高度func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {let ContentNum = Content[indexPath.row]//计算内容高度(ContentSize.width/170计算有多少行文字)let ContentSize = ContentNum.boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil)let cellHeight = ContentSize.height*(ContentSize.width/170)if cellHeight < 30{return 30}else{return cellHeight}}//根据数据源内容来设置UITableView高度(+50防止内容拥挤)func setContentForTable(_ content:[String]){self.Content = contentvar tableHeight:CGFloat = 0for i in 0..<content.count{let ContentSize = Content[i].boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil)tableHeight += ContentSize.height*(ContentSize.width/170)}tableView.frame = CGRect(x: 20, y: 0, width: 300, height: tableHeight + 50)tableView.reloadData()}func getMyHeight()->CGFloat{return tableView.frame.size.height}required init?(coder aDecoder: NSCoder) {fatalError("init(coder:) has not been implemented")}}

编辑ViewController:

import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{var articles = ["徐志摩","克莱儿▪麦克福尔","东野圭吾"]var Contents = [["我是天空里的一片云,偶尔投影在你的波心,你不必讶异,更无须欢喜,在转瞬间消灭了踪影。你我相逢在黑夜的海上,你有你的,我有我的,方向,你记得也好,最好你忘掉,在这交会时互放的光亮"],["当灵魂休眠的时候,我敢肯定它们得到了片刻的平静和安宁。111111111111111111111111"],["你我都不可能摆脱时钟的束缚,彼此都已沦为社会这个时钟的齿轮,一旦少了齿轮,时钟就会出乱子。纵然自己渴望率性而为,周遭也不容许,我们虽然得到了安定,但失去自由也是不争的事实。"]]override func viewDidLoad() {super.viewDidLoad()let tabView = UITableView(frame:CGRect(x: 0, y: 20, width: self.view.bounds.width, height: self.view.bounds.height))tabView.delegate = selftabView.dataSource = selftabView.separatorStyle = .noneself.view.addSubview(tabView)}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return articles.count*2}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let idA = "cellForArticles"let idB = "cellForContent"var cell1:UITableViewCell?var cell2:CustomizeTableViewCell?if indexPath.row%2 == 0{cell1 = tableView.dequeueReusableCell(withIdentifier: idA)if cell1 == nil{cell1 = UITableViewCell(style: .default, reuseIdentifier: idA)}cell1?.textLabel?.text = articles[indexPath.row/2]cell1?.textLabel?.textColor = UIColor.graycell1?.backgroundColor = UIColor.blackcell1?.textLabel?.font = UIFont.systemFont(ofSize: 16)return cell1!}else{cell2 = tableView.dequeueReusableCell(withIdentifier: idB) as? CustomizeTableViewCellif cell2 == nil{cell2 = CustomizeTableViewCell(style: .default, reuseIdentifier: idB)}let content = Contents[indexPath.row/2]cell2?.setContentForTable(content)return cell2!}}func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {if indexPath.row % 2 == 0{return 40}else{let Content = Contents[indexPath.row/2]var cellHeight:CGFloat = 0for i in 0..<Content.count{let ContentSize = Content[i].boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil)cellHeight += ContentSize.height*(ContentSize.width/170)}return cellHeight + 50}}
}

滚动到底部

使用scrollToRow方法滚动到最后一行

let secon = 1 //最后一个分组的索引(0开始,如果没有分组则为0)
let rows = 10 //最后一个分组最后一条项目的索引
let indexPath = IndexPath(row: rows, section: secon)
self.tableView?.scrollToRow(at: indexPath, at:.bottom, animated: true)

使用setContentOffset设置偏移量实现滚动:

let offset = CGPoint(x:0, y:self.tableView!.contentSize.height- self.tableView!.bounds.size.height)
self.tableView!.setContentOffset(offset, animated: true)

Swift - UITableView相关推荐

  1. Swift - UITableView状态切换效果

    Swift - UITableView状态切换效果 效果 源码 https://github.com/YouXianMing/Swift-Animations // // TableViewTapAn ...

  2. Swift - UITableView里的cell底部分割线左侧靠边

    override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, ...

  3. iOS swift UITableView的cell被点击或是用代码选中其中的UIImageView会显示Highlighted效果

    文章目录 1.展示 2.cell的代码选中不能用cell.isSelected,而要用tableView.selectRow( 1.展示 2.cell的代码选中不能用cell.isSelected,而 ...

  4. Swift UITableView嵌套UICollectionView点击事件冲突(点击事件穿透)

    不管是啥都响应tableviewcell class JYShopCertificationCell: UITableViewCell { override func hitTest(_ point: ...

  5. Swift的一些问题

    一些Swift的问题列表: How to use a Objective-C #define from Swift How do I convert an NSDictionary to a Swif ...

  6. iOS Swift 高仿微信

    LXFWeChat Swift 3.0 高仿微信 两个测试账号: lxf lqr  密码都是123456 源码地址 码云 http://git.oschina.net/LinXunFeng/LXFWe ...

  7. iOS - Swift 高仿微信

    LXFWeChat Swift 3.0 高仿微信 源码地址 码云 https://git.oschina.net/coderlxf/LXFWeChat GitHub https://github.co ...

  8. php安卓直播抓取,hls,android_安卓大部分浏览器播放HLS协议直播流会从头开始,hls,android,ffmpeg,m3u8 - phpStudy...

    安卓大部分浏览器播放HLS协议直播流会从头开始 遇到的问题 HLS直播流在iOS系统中表现正常, 但在安卓使用大部分浏览器(UC浏览器除外)播放ffmpeg生成的HLS直播流都会发生从头播放的问题, ...

  9. IOS精品源码,仿探探UIButton封装iOS提示弹框迅速引导页自定义导航栏

    1.仿 探探UI Swift ,重用机制 2.超强UIButton封装 3.一行代码集成UIPickerView,界面完全自定义 4.iOS提示弹框 5.swift UITableView / UIC ...

最新文章

  1. c语言实验七 函数实验报告,C语言实验七函数实验报告.doc
  2. 线性代数笔记:Hadamard积
  3. Microsoft CryptoAPI加密技术(一)
  4. CSDN社区之星专訪:我的蜕变之路
  5. 在架设网站服务器时,实习实习报告网站服务器架设.doc
  6. ropgadgets与ret2syscall技术原理
  7. java 图片压缩100k_java实现图片压缩
  8. idea 编译spring_Spring 源码阅读环境的搭建
  9. .net面试题及答案(一)(转)
  10. (转)基于MVC4+EasyUI的Web开发框架形成之旅--权限控制
  11. 大一java怎么学好_是否应该学习第二门语言,学那个比较合适。
  12. [转]mysql下如何执行sql脚本
  13. .net 3.5 数据库开发 之 LINQ 上
  14. 安装phpDocumentor
  15. Python2笨方法学习Python--习题二:注释和井号
  16. navicat 8.0 mysql 名、组织、注册码
  17. 章草、今草、狂草是草书的三种书写表现方式,你更喜欢哪一种?
  18. 同比 数据模型 环比_同比和环比计算公式?
  19. C#企业微信邮箱发送邮件问题_Error: authentication failed, system busy
  20. ubuntu显示隐藏文件

热门文章

  1. 【Pycharm教程】PyCharm 安装、卸载和升级包
  2. HTML是什么?—零基础自学网页制作
  3. 1587 例题3 [SCOI2009] Windy 数(Bzoj1026 LOJ LUOGU2657 提高+/省选-) 需考虑前导0的数位DP
  4. 联想Z5刷android11,联想Z5 Pro GT升级安卓10 ZUI_11.5.141稳定版-支持TWRP偷渡升级
  5. 联想z5 Android 9.0,联想Z5 Pro(安卓9.0)刷机教程 联想Z5 Pro刷机图解
  6. 学习自旋电子学的笔记01:微磁模拟软件OOMMF的教程(中文版)16章
  7. ubantu安装网易云
  8. DPL,RPL,CPL 之间的联系和区别
  9. 博图pro版和adv版区别_redmi k30 pro变焦版区别评测 DxoMark相机评分公布
  10. 成事的人,往往是谦逊的