swift之UICollectionView的使用、cell多选

UICollectionview代理方法的执行顺序:

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

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView)

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

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

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

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)

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

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView)

 

 

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

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

参考:https://blog.csdn.net/qq_22157341/article/details/79184479

重点:allowsMultipleSelection = true

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

/**
 cell多选,https://blog.csdn.net/qq_22157341/article/details/79184479
 全部选中、全部取消、单个选中、单个取消
 */
import UIKit

class 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 UIKit

class 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 UIKit

class 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 UIKit

class 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 UIKit

class 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

    }()

}

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
UICollectionView是一种用于展示多种类型的可滚动视图的类,它在Swift中也可使用。它是UIKit框架中的一部分,提供了一个灵活的方式来展示和管理大量的数据。 使用UICollectionView是为了展示具有多种布局和组件的数据集合。它类似于UITableView,但比UITableView更强大,可以支持多行或多列的自定义布局。 使用UICollectionView时,首先需要创建一个UICollectionViewLayout对象来定义布局。布局包含了单元格的大小、间距、滚动方向等信息。 然后,需要创建一个UICollectionView对象,并设置数据源和委托。数据源用于提供内容,委托用于处理用户交互和其他自定义操作。 接下来,实现UICollectionViewDataSource协议的方法,用于提供单元格的数量和内容。通常需要创建一个UICollectionViewCell的子类,并在数据源方法中使用该单元格。 然后,可以通过UICollectionViewDelegate协议的方法来响应选中单元格的操作,并执行相关的操作,如打开新的视图控制器或执行其他自定义操作。 最后,将UICollectionView添加到视图中,并通过reloadData()方法加载和刷新数据。 使用UICollectionView时,还可以自定义单元格的外观、动画效果和交互行为,以满足特定的设计要求。 在Swift中,可以使用UICollectionViewFlowLayout来快速创建简单的网格布局。同时,也可以使用自定义的布局来实现更复杂的布局需求,如瀑布流布局、层叠布局等。 总的来说,UICollectionView是一种强大而灵活的视图类,在Swift中可以方便地使用,用于展示和管理多种类型的数据集合。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值