本文共 38165 字,大约阅读时间需要 127 分钟。
1:当创建UITableViewCell的时候使用Auto Layout布局子视图,添加对应的约束( leading, top, trailing and bottom constraints)
2:设置tableView的rowHeight为UITableViewAutomaticDimension
3:设置estimatedRowHeight或者是实现预估高度代理方法,该值非0即可,或者设置为cell的一半
设置estimatedRowHeight表示为cell设置一个临时的高度或者说是占位高度。滚动tableView的时候当cell即将出屏幕时,cell的高度即将被计算,为了确定cell实际的高度,tableView会询问每一个cell的高度,而cell的高度是基于它的contentView的高度,由于我们在布局的时候使用了Auto Layout为contentView添加了与子视图之间的约束,所以会进行自动计算。一旦cell实际的高度被确定,之前设置的estimatedRowHeight会被更新到实际的高度值。
注意:在使用了Auto Layout进行自动计算cell之后,我们不在需要实现代理方法tableView:heightForRowAtIndexPath:设置高度了
1.************(个人中心)tablview的简单用法、侧滑删除,在view中********
/** 普通的tableviewHeader使用: let muselectcell = LYBNormalTablview.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: HEIGHT)) view.addSubview(muselectcell) */import UIKit@available(iOS 11.0, *)class LYBNormalTablview: UIView ,UITableViewDelegate,UITableViewDataSource{ override init(frame: CGRect) { super.init(frame: frame) setTable() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView:UITableView, numberOfRowsInSection section: Int) -> Int { return titArr.count; } func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:LYBnormalTabcell=tableView.dequeueReusableCell(withIdentifier:"normalcell")as!LYBnormalTabcell if(imageArr.count>0){cell.imageStr=imageArr[indexPath.row] } if(titArr.count>0){ cell.titlestr=titArr[indexPath.row] } return cell } func tableView(_ tableView:UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) // swift4中通过字符串名转化成类,需要在字符串名前加上项目的名称// let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"]as? String//这是获取项目的名称,// let className=clsName! + "." + self.classArr[indexPath.row]// let viewC = NSClassFromString(className)!as! UIViewController.Type //这里需要指定类的类型XX.Type// let vc=viewC.init() } //cell高度 func tableView(_ tableView:UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } // func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // return 20 // } // func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // return "第一组" // } func setTable() { tab.tableFooterView=UIView.init() tab.delegate=self tab.dataSource=self addSubview(tab) //注册cell---UITableViewCell.classForCoder()或者UITableViewCell.self tab.register(LYBnormalTabcell.self, forCellReuseIdentifier:"normalcell") tab.showsVerticalScrollIndicator=false tab.contentInsetAdjustmentBehavior=UIScrollView.ContentInsetAdjustmentBehavior.always //组头 let nomalheader:LYBNormalTableviewHeader=LYBNormalTableviewHeader.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: 200)) tab.tableHeaderView=nomalheader //组尾 let phoneBtn:UIButton=UIButton.init(frame:CGRect(x:0,y:0,width:WIDTH,height:50)) phoneBtn.setTitle("客服热线:4000-010-313", for:UIControl.State.normal) phoneBtn.setTitleColor(UIColor.init(red:59.0/255, green:122.0/255, blue:246.0/255, alpha:1), for: UIControl.State.normal) phoneBtn.setImage(UIImage.init(named:"bottomPhone"), for:UIControl.State.normal) phoneBtn.imageEdgeInsets=UIEdgeInsets(top:0, left: -20, bottom:0, right: 0) phoneBtn.titleEdgeInsets=UIEdgeInsets(top:0, left: 0, bottom:0, right: 0) tab.tableFooterView=phoneBtn phoneBtn.addTarget(self, action:#selector(phoneCall), for:UIControl.Event.touchUpInside) } @objc func phoneCall() { print("打电话") } //标题数组 lazy var titArr:[String]={ let titAr=["第一","第二","第三","第四","第五","第六","第七","关于我们"] return titAr }() //图片数组 lazy var imageArr:[String]={ return ["appstart","fenxiangcai","appstart","fenxiangcai","appstart","appstart","icon_tab_mine_sel","appstart"] }() //类名数组 lazy var classArr:[String] = { let classAr=["LYBMyHongbaoVC","LYBMyNewPeopleUseVC","LYBMyJiazuVC","LYBMytradeVC","LYBMyBankListVC","LYBMyReaNameVC","LYBMyproblemVC","LYBMyAboutMeVC"] return classAr }() //懒加载---tab lazy var tab:UITableView = { var tabv=UITableView.init(frame:CGRect(x:0,y:-TopSpaceHigh,width:Int(WIDTH),height:Int(HEIGHT)-49+Int(TopSpaceHigh)-Int(bottomSafeHeight)), style: UITableView.Style.plain) return tabv }() //懒加载---imageview----暂时没用到 lazy var imageV:UIImageView = { let IMV = UIImageView.init(frame:CGRect(x:0,y:0,width:100,height:100)) return IMV }()//=====================2.侧滑删除操作//侧滑删除操作func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { //删除 let del:UITableViewRowAction=UITableViewRowAction.init(style: UITableViewRowAction.Style.destructive, title: "删除") { (del, indexpath) in //执行删除的代码 }let cancel:UITableViewRowAction=UITableViewRowAction.init(style: UITableViewRowAction.Style.default, title: "取消") { (cancel, indexPath) in } cancel.backgroundColor=UIColor.blue return [del,cancel] } //ios14的侧滑删除 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let delet = UIContextualAction(style: .destructive, title: "删除") { action, view, completionHandler in print("删除") tableView.setEditing(false, animated: true) completionHandler(true) } let cancel = UIContextualAction(style: .normal, title: "取消", handler: { (action,view,completionHandler ) in print("取消") tableView.setEditing(false, animated: true) completionHandler(true) })let actions = UISwipeActionsConfiguration(actions: [delet,cancel]) // 禁止侧滑无线拉伸 actions.performsFirstActionWithFullSwipe = false; return actions }}********/*** 普通cell */import UIKitclass LYBnormalTabcell: UITableViewCell { var imageStr:String="appstart"{ didSet{imagev.image=UIImage.init(named: imageStr) } } var titlestr:String=""{ didSet{ tetxtlab.text=titlestr } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initViews(){ addSubview(imagev) addSubview(tetxtlab) addSubview(arrowImagev) } //左边的图片 lazy var imagev:UIImageView={ let imageV:UIImageView = UIImageView.init(frame: CGRect.init(x: 20, y: 10, width: 30, height:30)) return imageV }() //中间的标题 lazy var tetxtlab:UILabel={ let textlbl:UILabel=UILabel.init(frame: CGRect.init(x: 80, y: 0, width: WIDTH/2, height: 50)) return textlbl }() lazy var arrowImagev:UIImageView={ let arrowImageV:UIImageView=UIImageView.init(frame: CGRect.init(x: WIDTH-50, y: 10, width: 20, height: 30)) arrowImageV.image=UIImage.init(named: "icon_list_arrow") return arrowImageV }()}*********/*** 普通的tableviewHeader */import UIKitclass LYBNormalTableviewHeader: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor=UIColor.blue } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }}
2.**********动态高度cell的tableview*********
/** 动态计算cell 高度,社区,论坛cell */import UIKit@available(iOS 11.0, *)class LYBDynamicCaculateCellHeightTabview: UIView ,UITableViewDelegate,UITableViewDataSource{ var cellH:CGFloat=10//cell高度 override init(frame: CGRect) { super.init(frame: frame) setTable() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView:UITableView, numberOfRowsInSection section: Int) -> Int { return nicknameStrArr.count; } func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:LYBDynamicCaculateCell=tableView.dequeueReusableCell(withIdentifier:"caculatecell")as!LYBDynamicCaculateCell if(imageiconArr.count>0){ cell.imageiconStr=imageiconArr[indexPath.row] } if(nicknameStrArr.count>0){ cell.nicknameStr=nicknameStrArr[indexPath.row] } if textcontentArr.count>0{ cell.textContent=textcontentArr[indexPath.row] } if(imageContentArr.count>0){ cell.contetnImagesArr=imageContentArr[indexPath.row] } cellH=cell.caculateCellHeight()//计算真实的高度 return cell } func tableView(_ tableView:UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) // swift4中通过字符串名转化成类,需要在字符串名前加上项目的名称 // let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"]as? String//这是获取项目的名称, // let className=clsName! + "." + self.classArr[indexPath.row] // let viewC = NSClassFromString(className)!as! UIViewController.Type //这里需要指定类的类型XX.Type // let vc=viewC.init() } //cell高度 func tableView(_ tableView:UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellH } // func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // return 20 // } // func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { // return "第一组" // } func setTable() { tab.tableFooterView=UIView.init() tab.delegate=self tab.dataSource=self addSubview(tab) //注册cell---UITableViewCell.classForCoder()或者UITableViewCell.self tab.register(LYBDynamicCaculateCell.self, forCellReuseIdentifier:"caculatecell") tab.showsVerticalScrollIndicator=false// tab.estimatedRowHeight=44;// tab.rowHeight=UITableView.automaticDimension; tab.contentInsetAdjustmentBehavior=UIScrollView.ContentInsetAdjustmentBehavior.always //组头 let nomalheader:LYBNormalTableviewHeader=LYBNormalTableviewHeader.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: 200)) tab.tableHeaderView=nomalheader //组尾 } //图片内容数组 lazy var imageContentArr:[[String]]={ let imageconteAr=[["appstart","fenxiangcai","fenxiangcai","fenxiangcai"],["fenxiangcai","fenxiangcai","fenxiangcai"],["appstart"],["fenxiangcai"],["appstart"],["appstart"],["icon_tab_mine_sel"],["appstart"]] return imageconteAr }() //文本内容数组 lazy var textcontentArr:[String]={ let texttcontents=["这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容这是第一个cell的内容","这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容","这是第三个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第三个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容","这是第四个cell的内容这是第二个cell的内容这是第二个cell的内容这是第四个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容","这是第五个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容","这是第六个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容","这是第七个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容","这是第八个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容这是第二个cell的内容"] return texttcontents }() //标题数组 lazy var nicknameStrArr:[String]={ let nicknameAr=["第一","第二","第三","第四","第五","第六","第七","关于我们"] return nicknameAr }() //图片数组 lazy var imageiconArr:[String]={ return ["appstart","fenxiangcai","appstart","fenxiangcai","appstart","appstart","icon_tab_mine_sel","appstart"] }() //类名数组 lazy var classArr:[String] = { let classAr=["LYBMyHongbaoVC","LYBMyNewPeopleUseVC","LYBMyJiazuVC","LYBMytradeVC","LYBMyBankListVC","LYBMyReaNameVC","LYBMyproblemVC","LYBMyAboutMeVC"] return classAr }() //懒加载---tab lazy var tab:UITableView = { var tabv=UITableView.init(frame:CGRect(x:0,y:-TopSpaceHigh,width:Int(WIDTH),height:Int(HEIGHT)-49+Int(TopSpaceHigh)-Int(bottomSafeHeight)), style: UITableView.Style.plain) return tabv }() //懒加载---imageview----暂时没用到 lazy var imageV:UIImageView = { let IMV = UIImageView.init(frame:CGRect(x:0,y:0,width:100,height:100)) return IMV }() //=====================2.侧滑删除操作 //侧滑删除操作 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { //删除 let del:UITableViewRowAction=UITableViewRowAction.init(style: UITableViewRowAction.Style.destructive, title: "删除") { (del, indexpath) in //执行删除的代码 } let cancel:UITableViewRowAction=UITableViewRowAction.init(style: UITableViewRowAction.Style.default, title: "取消") { (cancel, indexPath) in } cancel.backgroundColor=UIColor.blue return [del,cancel] } }***********/** 动态计算cell 高度 */import UIKitclass LYBDynamicCaculateCell: UITableViewCell { var imagevicon:UIImageView=UIImageView.init(frame: CGRect.init(x: 20, y: 10, width: 50, height: 50))//头像 var titlab:UILabel=UILabel.init(frame: CGRect.init(x: 20, y: 60, width: 100, height: 30))//昵称 //头像 var imageiconStr:String="appstart"{ didSet{ imagevicon.image=UIImage.init(named: imageiconStr) } } //昵称 var nicknameStr:String=""{ didSet{ titlab.text=nicknameStr } } //文字内容 var textContent:String=""{ didSet{ contentlabel.text=textContent } } //图片内容 var contetnImagesArr:[String]=[]{ didSet{ } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initViews(){ addSubview(titleView) addSubview(contentimageview) addSubview(contentlabel) addSubview(bottomView) } //计算并返回cell高度 func caculateCellHeight()->(CGFloat){ /** 计算文本的高度 */ let sizefont:CGFloat=15 //计算文本的大小 let textFont:UIFont=UIFont.systemFont(ofSize:sizefont)//注意:这里设置的大小要和文本的字体大小一致 contentlabel.font=UIFont.systemFont(ofSize: sizefont) //也可以直接用swift的字符串,不用转成Sting let boundingBox = contentlabel.text!.boundingRect(with: CGSize(width:WIDTH , height:500), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: textFont], context: nil).height print("---\(boundingBox)") contentlabel.height=boundingBox /** 计算图片的高度 */ /* 单图会按照图片等比例显示 多图的图片大小固定 多图如果是4张,会按照 2 * 2 显示 多图其他数量,按照 3 * 3 九宫格显示 */ let imgcontentviewheight:CGFloat=0; let w:Int=Int((UIScreen.main.bounds.size.width-40)/3); let count:Int = contetnImagesArr.count; let row:Int=(count-1)/3+1;//确定行数 var h:CGFloat=0;//cell 的高度 //设置文字的起始位置 contentimageview.y = titleView.height+contentlabel.height if contetnImagesArr.count==0{ contentimageview.height=imgcontentviewheight; }else { contentimageview.height=CGFloat(row)*CGFloat(w); } //******清空imgContentView上的内容******* for view in contentimageview.subviews{ view.removeFromSuperview() } //***********创建图片(i%3*w,i/3*w, w, w) for i in 0..
3.*********设置中心**********
/**设置 **/import UIKit@available(iOS 11.0, *)class LYBSettingTableview: UIView ,UITableViewDelegate,UITableViewDataSource{ override init(frame: CGRect) { super.init(frame: frame) setTable() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView:UITableView, numberOfRowsInSection section: Int) -> Int { if section==1{ return 1 } return titArr.count } func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:LYBSettingcell=tableView.dequeueReusableCell(withIdentifier:"LYBSettingcell")as!LYBSettingcell if indexPath.section==0{ if(imageArr.count>0){ cell.imageStr=imageArr[indexPath.row] } if(titArr.count>0){ cell.titlestr=titArr[indexPath.row] } }else if indexPath.section==1{ let cell:LYBSettingOutcell=tableView.dequeueReusableCell(withIdentifier: "LYBSettingOutcell") as! LYBSettingOutcell cell.selectionStyle=UITableViewCell.SelectionStyle.none return cell } return cell } func tableView(_ tableView:UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) // swift4中通过字符串名转化成类,需要在字符串名前加上项目的名称 // let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"]as? String//这是获取项目的名称, // let className=clsName! + "." + self.classArr[indexPath.row] // let viewC = NSClassFromString(className)!as! UIViewController.Type //这里需要指定类的类型XX.Type // let vc=viewC.init() if indexPath.section==1{ print("推出按钮") } } //cell高度 func tableView(_ tableView:UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section==1{ return 50 } return 0 }func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return " "} func setTable() { tab.tableFooterView=UIView.init() tab.delegate=self tab.dataSource=self addSubview(tab) tab.separatorStyle=UITableViewCell.SeparatorStyle.none //注册cell---UITableViewCell.classForCoder()或者UITableViewCell.self tab.register(LYBSettingcell.self, forCellReuseIdentifier:"LYBSettingcell") tab.register(LYBSettingOutcell.self, forCellReuseIdentifier:"LYBSettingOutcell") tab.showsVerticalScrollIndicator=false tab.contentInsetAdjustmentBehavior=UIScrollView.ContentInsetAdjustmentBehavior.always } //标题数组 lazy var titArr:[String]={ let titAr=["清理缓存","版本更新","关于我们"] return titAr }() //图片数组 lazy var imageArr:[String]={ return ["appstart","fenxiangcai","appstart"] }() //类名数组 lazy var classArr:[String] = { let classAr=["","",""] return classAr }() //懒加载---tab lazy var tab:UITableView = { var tabv=UITableView.init(frame:CGRect(x:0,y:0,width:Int(WIDTH),height:Int(HEIGHT)-49+Int(TopSpaceHigh)-Int(bottomSafeHeight)), style: UITableView.Style.plain) return tabv }() }************/* 设置的cell **/import UIKitclass LYBSettingcell: UITableViewCell { var imageStr:String="appstart"{ didSet{ imagev.image=UIImage.init(named: imageStr) } } var titlestr:String=""{ didSet{ tetxtlab.text=titlestr } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initViews(){ addSubview(imagev) addSubview(tetxtlab) addSubview(arrowImagev) addSubview(sepline)//分割线 } //左边的图片 lazy var imagev:UIImageView={ let imageV:UIImageView = UIImageView.init(frame: CGRect.init(x: 20, y: 10, width: 30, height:30)) return imageV }() //中间的标题 lazy var tetxtlab:UILabel={ let textlbl:UILabel=UILabel.init(frame: CGRect.init(x: 80, y: 0, width: WIDTH/2, height: 50)) return textlbl }() lazy var arrowImagev:UIImageView={ let arrowImageV:UIImageView=UIImageView.init(frame: CGRect.init(x: WIDTH-70, y: 10, width: 20, height: 30)) arrowImageV.image=UIImage.init(named: "icon_list_arrow") return arrowImageV }() lazy var sepline:UIView={ let sepl:UIView=UIView.init(frame: CGRect.init(x: 0, y: self.frame.size.height-1 , width: WIDTH, height: 1)) sepl.backgroundColor=UIColor.gray return sepl }()}***********/** 设置中,退出cell */import UIKitclass LYBSettingOutcell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initViews(){ addSubview(loginoutlabel) } lazy var loginoutlabel:UILabel={ let outlabel:UILabel=UILabel.init(frame: CGRect.init(x: 30, y: 0, width: WIDTH-60, height: 50)) outlabel.backgroundColor=UIColor.orange outlabel.text="退出" outlabel.textAlignment=NSTextAlignment.center outlabel.layer.cornerRadius=25 outlabel.clipsToBounds=true return outlabel }()}
4*********.简单的Tableview,在控制器中导航航透明******
import UIKit
import Kingfisher
var identifier="mycell"
class LYBMyVC: LYBBaseVC,UITableViewDataSource,UITableViewDelegate{
override func viewWillAppear(_ animated:Bool) { //导航透明self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)self.navigationController?.navigationBar.shadowImage=UIImage() } override func viewDidDisappear(_ animated:Bool) {// //取消透明导航// self.navigationController?.navigationBar.setBackgroundImage(nil, for: UIBarMetrics.default)// self.navigationController?.navigationBar.shadowImage=nil } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView:UITableView, numberOfRowsInSection section: Int) -> Int { return titArr.count; } func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell=tableView.dequeueReusableCell(withIdentifier:identifier) cell?.imageView?.image=UIImage.init(named:imageArr[indexPath.row]) cell?.textLabel?.text=titArr[indexPath.row] cell?.accessoryType=UITableViewCellAccessoryType.disclosureIndicator return cell! } func tableView(_ tableView:UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) // swift4中通过字符串名转化成类,需要在字符串名前加上项目的名称 let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"]as? String//这是获取项目的名称, let className=clsName! + "." + self.classArr[indexPath.row] let viewC = NSClassFromString(className)!as! UIViewController.Type //这里需要指定类的类型XX.Type let vc=viewC.init() self.navigationController?.pushViewController(vc, animated:true) } func tableView(_ tableView:UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } // func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {// return 20// }// func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {// return "第一组"// } func setTable() { tab.tableFooterView=UIView.init() tab.delegate=self tab.dataSource=self view.addSubview(tab) //注册cell---UITableViewCell.classForCoder()或者UITableViewCell.self tab.register(UITableViewCell.self, forCellReuseIdentifier:identifier)tab.showsVerticalScrollIndicator=falsetab.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentBehavior.always let nib = UINib(nibName: "LYBMyHeaderView", bundle:nil) let v = nib.instantiate(withOwner:nil, options: nil)[0]as! LYBMyHeaderView tab.tableHeaderView=v let phoneBtn:UIButton=UIButton.init(frame:CGRect(x:0,y:0,width:WIDTH,height:50)) phoneBtn.setTitle("客服热线:4000-010-313", for:UIControlState.normal) phoneBtn.setTitleColor(UIColor.init(red:59.0/255, green:122.0/255, blue:246.0/255, alpha:1), for: UIControlState.normal) phoneBtn.setImage(UIImage.init(named:"bottomPhone"), for:UIControlState.normal) phoneBtn.imageEdgeInsets=UIEdgeInsets(top:0, left: -20, bottom:0, right: 0) phoneBtn.titleEdgeInsets=UIEdgeInsets(top:0, left: 0, bottom:0, right: 0) tab.tableFooterView=phoneBtn phoneBtn.addTarget(self, action:#selector(phoneCall), for:UIControlEvents.touchUpInside) //上啦刷新 } @objc func phoneCall() { print("打电话") } override func viewDidLoad() { super.viewDidLoad() setTable() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //标题数组 lazy var titArr:[String]={ let titAr=["我的红包","新手教程","我的家族","我的交易","我的银行卡","实名认证","常见问题","关于我们"] return titAr }() //图片数组 lazy var imageArr:[String]={return ["hongbao","xinshoujiaocheng","jiazu","zhangdan","mycard","shimin","wenhao","guanyu"] }() //类数组 lazy var classArr:[String] = { let classAr=["LYBMyHongbaoVC","LYBMyNewPeopleUseVC","LYBMyJiazuVC","LYBMytradeVC","LYBMyBankListVC","LYBMyReaNameVC","LYBMyproblemVC","LYBMyAboutMeVC"] return classAr }() //懒加载---tab lazy var tab:UITableView = { var tabv=UITableView.init(frame:CGRect(x:0,y:-64,width:WIDTH,height:HEIGHT-49+64), style: UITableViewStyle.plain) if HEIGHT==812{ tabv=UITableView.init(frame:CGRect(x:0,y:-64,width:WIDTH,height:HEIGHT-34-49+64), style: UITableViewStyle.plain) } return tabv }() //懒加载---imageview lazy var imageV:UIImageView = { let IMV = UIImageView.init(frame:CGRect(x:0,y:0,width:100,height:100)) return IMV }() }=====================2.侧滑删除操作 //侧滑删除操作 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { //删除 let del:UITableViewRowAction=UITableViewRowAction.init(style: UITableViewRowActionStyle.destructive, title: "删除") { (del, indexpath) in //执行删除的代码 } let cancel:UITableViewRowAction=UITableViewRowAction.init(style: UITableViewRowActionStyle.default, title: "取消") { (cancel, indexPath) in //可以不写任何代码,也可以执行其他操作 } cancel.backgroundColor=UIColor.blue return [del,cancel] }
4.********tabbleviewcell多选********
OC中使用:
编辑状态UITableViewCellEditingStyle有三种模式:
多选框的风格, 只需要风格同时包含UITableViewCellEditingStyleDelete和UITableViewCellEditingStyleInsert就可以
通过获取选中的cell的indexpath实现:tab.indexPathsForSelectedRows
tab.allowsMultipleSelection=YES//允许多选
***************
swift使用,记录索引的方式实现
/** tableviewcell多选,用的是记录索引的方法 */import UIKit@available(iOS 11.0, *)class LYBMutipleSelectCellTableview: UIView ,UITableViewDelegate,UITableViewDataSource{ //存储选中单元格的索引 var selectedIndexs = [Int]() override init(frame: CGRect) { super.init(frame: frame) addSubview(sureAndCancelView) setTable() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView:UITableView, numberOfRowsInSection section: Int) -> Int { return titArr.count } func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:LYBmutipleSelectTabcell=tableView.dequeueReusableCell(withIdentifier:"LYBmutipleSelectTabcell")as!LYBmutipleSelectTabcell if(imageArr.count>0){ cell.imageStr=imageArr[indexPath.row] } if(titArr.count>0){ cell.titlestr=titArr[indexPath.row] } //判断是否选中(选中单元格尾部打勾) if selectedIndexs.contains(indexPath.row) {// cell.accessoryType = .checkmark cell.isSelect=true } else {// cell.accessoryType = .none cell.isSelect=false } cell.selectionStyle=UITableViewCell.SelectionStyle.none return cell } //cell高度 func tableView(_ tableView:UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } //选中cell func tableView(_ tableView:UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) //判断该行原先是否选中 if let index = selectedIndexs.index(of: indexPath.row){ selectedIndexs.remove(at: index) //原来选中的取消选中 }else{ selectedIndexs.append(indexPath.row) //原来没选中的就选中 } 刷新该行 tab.reloadRows(at: [indexPath], with: .automatic) print("选中的cell\(selectedIndexs)") } func setTable() { tab.tableFooterView=UIView.init() tab.delegate=self tab.dataSource=self addSubview(tab) tab.separatorStyle=UITableViewCell.SeparatorStyle.none //注册cell---UITableViewCell.classForCoder()或者UITableViewCell.self tab.register(LYBmutipleSelectTabcell.self, forCellReuseIdentifier:"LYBmutipleSelectTabcell") tab.showsVerticalScrollIndicator=false tab.contentInsetAdjustmentBehavior=UIScrollView.ContentInsetAdjustmentBehavior.always } //标题数组 lazy var titArr:[String]={ let titAr=["清理缓存","版本更新","关于我们"] return titAr }() //图片数组 lazy var imageArr:[String]={ return ["appstart","fenxiangcai","appstart"] }() //懒加载---tab lazy var tab:UITableView = { var tabv=UITableView.init(frame:CGRect(x:0,y:50,width:Int(WIDTH),height:Int(HEIGHT)-49+Int(TopSpaceHigh)-Int(bottomSafeHeight)), style: UITableView.Style.plain) return tabv }() lazy var sureAndCancelView:UIView={ let v:UIView=UIView.init(frame: CGRect.init(x: 0, y: 0, width: Int(WIDTH), height: 50)) let cancelBtn:UIButton=UIButton.init(frame: CGRect.init(x: 20, y: 0, width: 100, height: 50)) cancelBtn.setTitle("取消", for: UIControl.State.normal) cancelBtn.addTarget(self, action: #selector(cancelClick), for: UIControl.Event.touchUpInside) cancelBtn.setTitleColor(UIColor.black, for: UIControl.State.normal) v.addSubview(cancelBtn) let sureBtn:UIButton=UIButton.init(frame: CGRect.init(x:WIDTH-120, y: 0, width: 100, height: 50)) sureBtn.setTitle("全选", for: UIControl.State.normal) sureBtn.addTarget(self, action: #selector(sureClick), for: UIControl.Event.touchUpInside) sureBtn.setTitleColor(UIColor.black, for: UIControl.State.normal) v.addSubview(sureBtn) return v }() //确定按钮 @objc func sureClick(sender:UIButton){ print("确定") selectAllcell(isselectOrcancel: true) } //取消按钮 @objc func cancelClick(sender:UIButton){ print("取消") selectAllcell(isselectOrcancel: false) } //cell全部选中或取消 func selectAllcell(isselectOrcancel:Bool){ selectedIndexs.removeAll() if isselectOrcancel{ for i in 0..
6.**********cell单选******
/** cell单选 **/import UIKit@available(iOS 11.0, *)class LYBsingleselctcellTabview: UIView ,UITableViewDelegate,UITableViewDataSource{ override init(frame: CGRect) { super.init(frame: frame) setTable() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView:UITableView, numberOfRowsInSection section: Int) -> Int { return titArr.count-1 } func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:LYBSingleselcettabcell=tableView.dequeueReusableCell(withIdentifier:"LYBSingleselcettabcell")as!LYBSingleselcettabcell if(imageArr.count>0){ cell.imageStr=imageArr[indexPath.row] } if(titArr.count>0){ cell.titlestr=titArr[indexPath.row] } cell.selectionStyle=UITableViewCell.SelectionStyle.none return cell } //cell高度 func tableView(_ tableView:UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } //选中cell func tableView(_ tableView:UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) tab.selectRow(at: indexPath, animated: true, scrollPosition: UITableView.ScrollPosition.none) //当前选中的cell// let cell:LYBSingleselcettabcell=tableView.cellForRow(at: indexPath)as! LYBSingleselcettabcell// cell.index=indexPath.row } func setTable() { tab.tableFooterView=UIView.init() tab.delegate=self tab.dataSource=self addSubview(tab) tab.separatorStyle=UITableViewCell.SeparatorStyle.none //注册cell---UITableViewCell.classForCoder()或者UITableViewCell.self tab.register(LYBSingleselcettabcell.self, forCellReuseIdentifier:"LYBSingleselcettabcell") tab.showsVerticalScrollIndicator=false tab.contentInsetAdjustmentBehavior=UIScrollView.ContentInsetAdjustmentBehavior.always } //标题数组 lazy var titArr:[String]={ let titAr=["清理缓存","版本更新","关于我们"] return titAr }() //图片数组 lazy var imageArr:[String]={ return ["appstart","fenxiangcai","appstart"] }() //懒加载---tab lazy var tab:UITableView = { var tabv=UITableView.init(frame:CGRect(x:0,y:50,width:Int(WIDTH),height:Int(HEIGHT)-49+Int(TopSpaceHigh)-Int(bottomSafeHeight)), style: UITableView.Style.plain) return tabv }() }**********/** cell单选 */import UIKitclass LYBSingleselcettabcell: UITableViewCell { var imageStr:String="appstart"{ didSet{ imagev.image=UIImage.init(named: imageStr) } } var titlestr:String=""{ didSet{ tetxtlab.text=titlestr } } 记录当前选中状态的索引// var index:Int=0{// didSet{// print("\(index)")// // }// } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initViews(){ addSubview(imagev) addSubview(tetxtlab) addSubview(arrowImagev) addSubview(sepline)//分割线 } //左边的图片 lazy var imagev:UIImageView={ let imageV:UIImageView = UIImageView.init(frame: CGRect.init(x: 20, y: 10, width: 30, height:30)) return imageV }() //中间的标题 lazy var tetxtlab:UILabel={ let textlbl:UILabel=UILabel.init(frame: CGRect.init(x: 80, y: 0, width: WIDTH/2, height: 50)) return textlbl }() lazy var arrowImagev:UIImageView={ let arrowImageV:UIImageView=UIImageView.init(frame: CGRect.init(x: WIDTH-70, y: 10, width: 30, height: 30)) arrowImageV.image=UIImage.init(named: "fuxuankuangUnselect") return arrowImageV }() lazy var sepline:UIView={ let sepl:UIView=UIView.init(frame: CGRect.init(x: 0, y: self.frame.size.height-1 , width: WIDTH, height: 1)) sepl.backgroundColor=UIColor.gray return sepl }() //当执行tab.selectRow(at: indexPath, animated: true, scrollPosition: UITableView.ScrollPosition.none)时会调用下面的方法,当前的cell选中,其他的cell就变成不选中的状态了 override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) print("---001-\(selected)") if selected{ arrowImagev.image=UIImage.init(named: "fuxuankuangselect") }else { print("---002-\(selected)") arrowImagev.image=UIImage.init(named: "fuxuankuangUnselect") } }}
转载地址:http://pimgi.baihongyu.com/