Swift - UITableView
发布时间:2020-12-14 05:06:37 所属栏目:百科 来源:网络整理
导读:创建UITablView import UIKitclass ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ var Names = ["A","B","C","D","E","F"] var tableView:UITableView! override func viewDidLoad() { super.viewDidLoad() //创建表格图 se
创建UITablViewimport UIKit class 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 = self self.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 = headerLabel self.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 = .checkmark print("你选择了:(String(describing: cell?.textLabel?.text))") }else{ cell?.accessoryType = .none } } } 使用不同样式单元格import UIKit class 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,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.gray self.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 UIKit class CustomizeTableViewCell: UITableViewCell { var UserImage:UIImageView! var UserName:UILabel! var Detail:UIButton! override init(style: UITableViewCell.CellStyle,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 UIKit class ViewController: UIViewController,UITableViewDelegate{ var user = ["A","C"] override func viewDidLoad() { super.viewDidLoad() let tableView = UITableView(frame: self.view.frame) tableView.dataSource = self tableView.delegate = self self.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? CustomizeTableViewCell if cell == nil{ cell = CustomizeTableViewCell(style: .default,reuseIdentifier: identifier) } cell?.UserName.text = user[indexPath.row] return cell! } } 给文章添加章节和索引import UIKit class ViewController: UIViewController,UITableViewDelegate{ var Section = ["A","F","G","H","I","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"]] var tableView:UITableView! override func viewDidLoad() { super.viewDidLoad() //创建表格图 self.tableView = UITableView(frame: self.view.frame,style: .grouped) self.tableView?.delegate = self self.tableView?.dataSource = self //创建表头标签 let headerLabel = UILabel(frame: CGRect(x: self.view.bounds.width/2,height: 30)) headerLabel.text = "添加章节和索引" self.tableView?.tableHeaderView = headerLabel self.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.section var data = self.Content[section] cell?.textLabel?.text = data[indexPath.row] return cell! } //点击单元格响应时间 func tableView(_ tableView: UITableView,animated: true)//使被点击的单元格的颜色立即恢复 let section = indexPath.section var 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 UIKit class ViewController: UIViewController,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 = self tableView.delegate = self //设置是否为编辑模式 tableView.setEditing(false,animated: true) self.view.addSubview(tableView) //添加一个手势来开启/关闭编辑模式 let Tap = UITapGestureRecognizer(target: self,action: #selector(OpenEdit)) Tap.numberOfTapsRequired = 2 Tap.numberOfTouchesRequired = 1 self.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.row let toRow = destinationIndexPath.row let formContent = Content[formRow] Content.remove(at: formRow) Content.insert(formContent,at: toRow) } } TableViewCell嵌套import UIKit class ViewController: UIViewController,UITableViewDelegate{ var articles = ["A","B"] var Contents = ["1","2"] override func viewDidLoad() { super.viewDidLoad() let tableView = UITableView(frame:self.view.frame) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none self.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 import UIKit class CustomizeTableViewCell: UITableViewCell,UITableViewDelegate { var tableView:UITableView! var Content:[String] = [] override init(style: UITableViewCell.CellStyle,reuseIdentifier: reuseIdentifier) //进行初始化,后续在进行更改 tableView = UITableView(frame: CGRect(x: 0,width: 300,height: 50)) tableView.dataSource = self tableView.delegate = self //设置是否允许滑动(设为false,防止内容跟着手指滑动而滑动) tableView.isScrollEnabled = false tableView.separatorStyle = .none self.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 = 0 return 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 = content var tableHeight:CGFloat = 0 for i in 0..<content.count { let ContentSize = Content[i].boundingRect(with: CGSize(),context: nil) tableHeight += ContentSize.height*(ContentSize.width/170) } tableView.frame = CGRect(x: 20,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 UIKit class ViewController: UIViewController,UITableViewDelegate{ var articles = ["徐志摩","克莱儿?麦克福尔","东野圭吾"] var Contents = [["我是天空里的一片云,偶尔投影在你的波心,你不必讶异,更无须欢喜,在转瞬间消灭了踪影。你我相逢在黑夜的海上,你有你的,我有我的,方向,你记得也好,最好你忘掉,在这交会时互放的光亮"],["当灵魂休眠的时候,我敢肯定它们得到了片刻的平静和安宁。222222222222222222221111"],["你我都不可能摆脱时钟的束缚,彼此都已沦为社会这个时钟的齿轮,一旦少了齿轮,时钟就会出乱子。纵然自己渴望率性而为,周遭也不容许,我们虽然得到了安定,但失去自由也是不争的事实。"]] override func viewDidLoad() { super.viewDidLoad() let tabView = UITableView(frame:CGRect(x: 0,y: 20,height: self.view.bounds.height)) tabView.delegate = self tabView.dataSource = self tabView.separatorStyle = .none self.view.addSubview(tabView) } 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.gray cell1?.backgroundColor = UIColor.black cell1?.textLabel?.font = UIFont.systemFont(ofSize: 16) return cell1! }else{ cell2 = tableView.dequeueReusableCell(withIdentifier: idB) as? CustomizeTableViewCell if 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 = 0 for i in 0..<Content.count{ let ContentSize = Content[i].boundingRect(with: CGSize(),context: nil) cellHeight += ContentSize.height*(ContentSize.width/170) } return cellHeight + 50 } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |