博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
swift之UICollectionView的使用、cell多选
阅读量:4289 次
发布时间:2019-05-27

本文共 16624 字,大约阅读时间需要 55 分钟。

UICollectionview代理方法的执行顺序:

//手指在屏幕上开始拖拽

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView)

//停止拖拽,手指离开了屏幕,

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)

//手动拖拽,手指离开了屏幕,滚动的cell停止加速度,减速完成(滚动停止)

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)

//停止滚动,自动滚动才执行,手势拖拽后停下来,这个方法不会执行

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView)

 

 

1.*************cell多选***********

包括:全部选中、全部取消、单个选中、单个取消

参考:

重点:allowsMultipleSelection = true

collec.indexPathsForSelectedItems保存着被选中item的indexPath;

/** cell多选,https://blog.csdn.net/qq_22157341/article/details/79184479 全部选中、全部取消、单个选中、单个取消 */import UIKitclass LYBMutipleSelectCellCollectionview: UIView ,UICollectionViewDelegate,UICollectionViewDataSource{    var collec:UICollectionView?     var indexpathArr:[IndexPath]=[]//选中的cell的indexpath数组        override init(frame: CGRect) {        super.init(frame: frame)        createCollectionView()    }        required init?(coder aDecoder: NSCoder) {        fatalError("init(coder:) has not been implemented")    }        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)    }    func createCollectionView(){        addSubview(sureAndCancelView)                let flowLayout = UICollectionViewFlowLayout.init()        flowLayout.itemSize=CGSize.init(width: WIDTH/4, height: WIDTH/4)        flowLayout.minimumLineSpacing=0        flowLayout.minimumInteritemSpacing=0//        flowLayout.headerReferenceSize = CGSize.init(width: WIDTH, height: 50)//组头的高度        collec = UICollectionView.init(frame: CGRect.init(x: 0, y: 50, width: Int(WIDTH), height: Int(HEIGHT)-Int(bottomSafeHeight)-Int(TopSpaceHigh)-50), collectionViewLayout: flowLayout)        collec?.backgroundColor=UIColor.white        collec?.delegate=self        collec?.dataSource=self        collec?.register(LYBMutipleselectcel.classForCoder(), forCellWithReuseIdentifier: "LYBMutipleselectcel")        collec?.allowsMultipleSelection=true        addSubview(collec!)    }        func numberOfSections(in collectionView: UICollectionView) -> Int {        return 1    }        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        return 12    }        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {                let cell:LYBMutipleselectcel = collectionView.dequeueReusableCell(withReuseIdentifier: "LYBMutipleselectcel", for: indexPath) as! LYBMutipleselectcel                cell.backgroundColor=UIColor.red        return cell    }    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {        return true    }       //选中cell,第一次点击是选中    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {           selectorcancel(collectionview: collectionView)         }     //选中cell后设置cell页面的内容状态    func selectorcancel(collectionview:UICollectionView){       //选中        indexpathArr=(collec?.indexPathsForSelectedItems)!//所有被选中的cell的indexpath        for indexpah in indexpathArr{            let cell:LYBMutipleselectcel=collec!.cellForItem(at: indexpah) as! LYBMutipleselectcel            cell.isSelect=true//重写cell的属性            cell.isSelected=true                   }  print("选中\(indexpathArr)")               }        //取消选中cell,第二次点击是取消    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {        indexpathArr=(collec?.indexPathsForSelectedItems)!//所有被选中的cell的indexpath        let cell:LYBMutipleselectcel=collec!.cellForItem(at: indexPath) as! LYBMutipleselectcel        cell.isSelect=false//重写cell的属性        cell.isSelected=false        print("取消\(indexpathArr)")    }            //cell全部选中或取消    func selectAllcell(isselectOrcancel:Bool){        indexpathArr=(collec?.indexPathsForVisibleItems)!//所有可见cell的indexpath        for indexpah in indexpathArr {                        let cell:LYBMutipleselectcel=collec!.cellForItem(at: indexpah) as! LYBMutipleselectcel            if isselectOrcancel{                collec?.selectItem(at: indexpah, animated: true, scrollPosition: UICollectionView.ScrollPosition.bottom)//设为选中状态                cell.isSelect=true//重写cell的属性                cell.isSelected=true                 indexpathArr=(collec?.indexPathsForSelectedItems)!//所有被选中的cell的indexpath            }else {                collec?.deselectItem(at: indexpah, animated: true)//取消选中的状态                cell.isSelect=false//重写cell的属性                cell.isSelected=false                indexpathArr=(collec?.indexPathsForSelectedItems)!//所有被选中的cell的indexpath            }        }               print("全选或取消\(String(describing: indexpathArr))")    }    }*************/** 多选cell */import UIKitclass LYBMutipleselectcel: UICollectionViewCell {        var imageV:UIImageView!var img:UIImage=UIImage.init(named: "center")!{        willSet(newimage) {            imageV.image= newimage //或者在didSet中使用imageV.image= img        }        didSet(oldvalue) {                   imageV.image= image//这里的img已经是新的值了        }            }    //是否选中    var isSelect:Bool=false{        didSet{            print("\(isSelect)")            if isSelect{                selectbtn.setImage(UIImage.init(named: "comm_btn_checkmark"), for: UIControl.State.normal)            }else {                selectbtn.setImage(UIImage.init(), for: UIControl.State.normal)            }        }    }    override init(frame: CGRect) {        super.init(frame: frame)        createCell()    }        required init?(coder aDecoder: NSCoder) {        fatalError("init(coder:) has not been implemented")    }            func createCell(){                imageV = UIImageView.init(frame:CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))        imageV.image=UIImage.init(named: "appstart")        addSubview(imageV)        addSubview(selectbtn)    }            lazy var selectbtn:UIButton={                let btn:UIButton=UIButton.init(frame: CGRect.init(x: 0, y: self.frame.size.width-50, width: 30, height: 30))        return btn    }()}

 

 

 

2.***********普通的collectionview使用*********

/*** 普通的collectionview */import UIKitclass LYBNormalcollectionview: UIView ,UICollectionViewDelegate,UICollectionViewDataSource {    var collec:UICollectionView?    override init(frame: CGRect) {        super.init(frame: frame)        createCollectionView()    }        required init?(coder aDecoder: NSCoder) {        fatalError("init(coder:) has not been implemented")    }        func createCollectionView(){        let flowLayout = UICollectionViewFlowLayout.init()        flowLayout.itemSize=CGSize.init(width: 100, height: 100)        flowLayout.headerReferenceSize = CGSize.init(width: WIDTH, height: 50)//组头的高度        collec = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: Int(WIDTH), height: Int(HEIGHT)-Int(bottomSafeHeight)-Int(TopSpaceHigh)), collectionViewLayout: flowLayout)        collec?.backgroundColor=UIColor.white        collec?.delegate=self        collec?.dataSource=self        collec?.register(LYBNOrmalCollectionviewcell.classForCoder(), forCellWithReuseIdentifier: "LYBNOrmalCollectionviewcell")              //注册组头        collec!.register(LYBCollectionviewHeader.classForCoder(), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "homeCollectionviewHeader")                       addSubview(collec!)    }        func numberOfSections(in collectionView: UICollectionView) -> Int {        return 1    }        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        return 5    }        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {                let cell:LYBNOrmalCollectionviewcell = collectionView.dequeueReusableCell(withReuseIdentifier: "LYBNOrmalCollectionviewcell", for: indexPath) as! LYBNOrmalCollectionviewcell                cell.backgroundColor=UIColor.red        return cell    }      //UICollectionElementKindSectionHeader和 kind 比较来区分header 和footer    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {  var headerView : LYBCollectionviewHeader = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "homeCollectionviewHeader", for: indexPath as IndexPath) as? LYBCollectionviewHeader)!        //分区头        if kind == UICollectionView.elementKindSectionHeader{      headerView = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "homeCollectionviewHeader", for: indexPath as IndexPath) as? LYBCollectionviewHeader)!     }     //分区尾        else if kind == UICollectionView.elementKindSectionFooter{             }     return headerView            }   }****************/** collectionviewcell */import UIKitclass LYBNOrmalCollectionviewcell: UICollectionViewCell {    var imageV:UIImageView!    var image:String="appstart"{        willSet(image) {                    }        didSet {                        imageV.image=UIImage.init(named: image)        }            }        override init(frame: CGRect) {        super.init(frame: frame)        createCell()    }        required init?(coder aDecoder: NSCoder) {        fatalError("init(coder:) has not been implemented")    }            func createCell(){                imageV = UIImageView.init(frame:CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height))        imageV.image=UIImage.init(named: "appstart")        addSubview(imageV)    }}**********/*** colllectionview组头 */import UIKitclass LYBCollectionviewHeader: UICollectionReusableView {    override init(frame: CGRect) {       super.init(frame: frame)         initViews()      }    func initViews(){ backgroundColor=UIColor.blue         addSubview(lab)         }       required init?(coder aDecoder: NSCoder) {fatalError("init(coder:) has not been implemented") }lazy var lab:UILabel={        let lbl=UILabel.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: self.frame.size.height))lbl.text="便民"   return lbl}()}

 

 

 

 

 

******************************

//组头

import UIKit

 

class LYBHomeconvienceCollectionHeaderViewCollectionReusableView: UICollectionReusableView {

    override init(frame: CGRect) {

        super.init(frame: frame)

       

        initViews()

    }

    func initViews(){

        backgroundColor=UIColor.blue

        addSubview(lab)

    }

    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    lazy var lab:UILabel={

       let lbl=UILabel.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: self.frame.size.height))

       lbl.text="便民"

        return lbl

        

    }()

}

*****************设置cell

//便民板块的cell

 

import UIKit

 

class LYBHomeConvienceCollectionViewCell: UICollectionViewCell {

 

    override init(frame: CGRect) {

        super.init(frame: frame)

        initViews()

    }

    func initViews(){

        addSubview(imageV)

        addSubview(lab)

        lab.backgroundColor=UIColor.white

    }

    required init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")

        

    }

    

    func setcell(imageStr:String,titleStr:String) {

        imageV.image=UIImage.init(named: imageStr)

        lab.text=titleStr

    }

    lazy var imageV:UIImageView={

       let imagev=UIImageView.init(frame: CGRect.init(x: 20, y: 20, width: WIDTH/4-40, height: WIDTH/4-40))

        

        return imagev

    }()

    

    lazy var lab:UILabel={

       let lbl=UILabel.init(frame: CGRect.init(x: 0, y: WIDTH/4, width: WIDTH/4, height: 30))

        lbl.textAlignment=NSTextAlignment.center

        lbl.font=UIFont.systemFont(ofSize: 13)

        return lbl

    }()

}

 

 

************************主控制器

import UIKit

 

class LYBConvinienceCollectionView: UIView,UICollectionViewDelegate,UICollectionViewDataSource{

    func numberOfSections(in collectionView: UICollectionView) -> Int {

        return 1

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

       

        return imageArr.count

    

    }

    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell:LYBHomeConvienceCollectionViewCell=collectionview.dequeueReusableCell(withReuseIdentifier: homeConvienceCollectionIdentifier, for: indexPath) as! LYBHomeConvienceCollectionViewCell

cell.setcell(imageStr: imageArr[indexPath.item], titleStr: titleArr[indexPath.item])

        return cell

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        collectionview .deselectItem(at: indexPath, animated: true)

    }

 

    

    //UICollectionElementKindSectionHeader和 kind 比较来区分header 和footer

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        var headerView : LYBHomeconvienceCollectionHeaderViewCollectionReusableView = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "homeCollectionviewHeader", for: indexPath as IndexPath) as? LYBHomeconvienceCollectionHeaderViewCollectionReusableView)!

        //分区头

        if kind == UICollectionElementKindSectionHeader{

            headerView = (collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "homeCollectionviewHeader", for: indexPath as IndexPath) as? LYBHomeconvienceCollectionHeaderViewCollectionReusableView)!

        }

            //分区尾

        else if kind == UICollectionElementKindSectionFooter{

            

            

        }

      

        return headerView

    }

    ***********//组头的高度---这个方法不执行;换成flow.headerReferenceSize = CGSize.init(width: WIDTH, height: 50)就可以了

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{

        

        return CGSize.init(width: WIDTH, height: 50)

        

    }

注意:设置组头的注意事项:

1.当前控制器遵守协议(UICollectionViewDelegateFlowLayout);

2.注意设置头部的size;
3. 当设置size,依然无法显示的原因:
-> 不要使用代理方法,(- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section);
->换成使用直接赋值方法(flowLayout.headerReferenceSize = CGSizeMake(xx, xx);).
4.未显示的原因:代理方法是最后才执行的.所以当内部添加了header之后,还没有走代理方法执行size,因此不会显示. 

    ***************

    override init(frame: CGRect) {

        super.init(frame: frame)

        initViews()

    }

    

    func initViews(){

        flow.itemSize=CGSize.init(width: WIDTH/4, height: WIDTH/4+30)

        flow.minimumLineSpacing=0

        flow.minimumInteritemSpacing=0

        addSubview(collectionview)

        collectionview.delegate=self

        collectionview.dataSource=self

        collectionview.backgroundColor=UIColor.white

*******flow.headerReferenceSize = CGSize.init(width: WIDTH, height: 50)//设置组头高度

        //注册cell

        collectionview .register(LYBHomeConvienceCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: homeConvienceCollectionIdentifier)

       

        //注册组头

       collectionview.register(LYBHomeconvienceCollectionHeaderViewCollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "homeCollectionviewHeader")

    }

    

    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    

    

    lazy var imageArr:[String] = {

       let imageAr=["lczq","banCredit","homeDaikuan","wfsc","sjcz","flowcz","mediaIcon","jtfk"]

        return imageAr

    }()

    

    lazy var titleArr:[String] = {

       let titleAr=["信用卡垫还","大额信用卡","贷款","商城","话费","流量","共享媒体","违章查询"]

        return titleAr

    }()

    

    lazy var flow:UICollectionViewFlowLayout = {

        let flo=UICollectionViewFlowLayout.init()

        return flo

    }()

    

    lazy var collectionview:UICollectionView = {

      let collect=UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: WIDTH, height: (WIDTH/4+30)*2+50), collectionViewLayout: flow)

       

        return collect

    }()

}

 

 

你可能感兴趣的文章
看透内存中的数组
查看>>
Android工程打包成jar文件,并且将工程中引用的jar一起打入新的jar文件中
查看>>
JS单例模式在工作中的使用
查看>>
Java易混小知识——equals方法和==的区别
查看>>
内置对象(Session、Application、ViewState)
查看>>
为什么Java有GC还需要自己来关闭某些资源?
查看>>
Android 热修复,插件式开发---基本知识
查看>>
JSP九大内置对象、四种作用域、跳转方式
查看>>
JSP 自定义标签
查看>>
JSP JavaBean
查看>>
从两个字符串中找出最大公共子字符串
查看>>
Java代码添加背景音乐
查看>>
Java面试题全集(上)
查看>>
JAVA泛型中的有界类型(extends super)
查看>>
炫酷进度条:Android 仿应用宝下载进度条
查看>>
Java程序内存的简单分析
查看>>
Javascript单例模式概念与实例
查看>>
SQL NULL 函数
查看>>
多例设计模式
查看>>
WebView的JavaScript与本地代码三种交互方式
查看>>