Swift3.0系列之UITableview和UICollectionView的联动

由于公司的项目是OC实现的,现在自己又在学swift,所以自己抽空写了swift版本的,目前整个项目完成了1/3吧。先看下今天要说的效果图:

联动.gif

这是基于上次iOS将数据从controller里分离出来减轻controller的压力这篇文章中的效果做的,只是那边是OC,现在用swift实现,这里就不分离数据了。

联动的原理:点击左边的tableView的时候刷新右边collectionView的数据源。

下面是代码实现(有几句关键代码我会提取出来以及重现几个开发中遇到的问题):

关键代码

一开始默认选中tableview的第0个row

 self.tableView(self.tableview, didSelectRowAt: NSIndexPath.init(row: 0, section: 0) as IndexPath)

tableview的didSelectRowAt indexPath代理实现

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        ///cell单选
        for i :Int in 0 ..< self.dataArr.count{
           let j:NSIndexPath = NSIndexPath.init(row: i, section: indexPath.section)
           let cell :UITableViewCell = tableView.cellForRow(at: j as IndexPath)!
            cell.backgroundColor = BACKGROUND_Color
            cell.textLabel?.textColor = .black
        }
        let cell :UITableViewCell = tableView.cellForRow(at: indexPath)!
        cell.backgroundColor = .clear
        cell.textLabel?.textColor = .red
        loadRightData(menuId: (self.leftData?.data?[indexPath.row].id)!)//获取到参数并加载右边数据
    }

开发中遇到的问题(可能是没去看swift的说明[尴尬])

由于右边的collectionView的section只需头部不需要尾部,所以只注册了header,在实现UICollectionViewDelegateFlowLayout代理的时候只实现了header的大小(和OC做法一致),然后Xcode给我报了个错,如下图:

error.jpeg

于是我除了返回header的大小,还返回了footer的大小

 //section头部高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSize(width:self.collection.frame.size.width,height:30)
    }
    //section尾部高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        
        return CGSize(width:self.collection.frame.size.width,height:0)
    }

具体代码实现

controller.swift代码

import UIKit
import HandyJSON
let ZLMCollectID = "item"
let ZLMHeaderID = "header"
class ZLMCategoryViewController: ZLMBaseViewController {

 var dataArr:Array<ZLMCateDataModel?> = []{ didSet { setDataSource() }
 }
 var rightDataArr:Array<CategoryModelList?> = []
 
 var leftData:ZLMCategoryModel?
 
 var rightData:ZLMCategoryRightModel?
 
 lazy var tableview :UITableView = {[weak self](result) in
     
     let tab = UITableView(frame: CGRect(x:0,y:64,width:ScreenW/4,        height:ScreenH-49))
     tab.delegate = self
     tab.dataSource = self
     tab.backgroundColor = BACKGROUND_Color
     tab.tableFooterView = UIView()//去除无数据的空tableViewCell
     return tab
 }()
 
 lazy var collection :UICollectionView = {
     
     let defaultLayout = UICollectionViewFlowLayout()
     
     defaultLayout.scrollDirection = UICollectionViewScrollDirection.vertical//设置垂直显示
     
     defaultLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)//设置边距
     
     defaultLayout.itemSize = CGSize(width:(ScreenW/4*3-10)/3, height: 100)
     
     defaultLayout.minimumLineSpacing = 5.0 //每个相邻的layout的上下间隔
     
     defaultLayout.minimumInteritemSpacing = 5.0 //每个相邻layout的左右间隔
     
     defaultLayout.headerReferenceSize = CGSize(width: 0, height: 0)
     
     defaultLayout.footerReferenceSize = CGSize(width: 0, height: 15)
     let collect = UICollectionView(frame:CGRect(x:ScreenW/4,y:64,width:ScreenW/4*3,height:ScreenH-49-64),collectionViewLayout: defaultLayout)
     
     collect.backgroundColor = .white
    //注册cell
     collect.register(UINib(nibName: "ZLMCateCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: ZLMCollectID)
    //注册头部
//        collect.register(ZLMHeaderCollectionReusableView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: ZLMHeaderID)  //用代码实现的view
     
     collect.register(UINib(nibName: "ZLMHeaderCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: ZLMHeaderID)//用xib实现的view
     
     collect.delegate = self
     
     collect.dataSource = self
     
     return collect
 }()

 override func viewDidLoad() {
     super.viewDidLoad()
     
    //自定义的一个自定义controller导航栏方法
    configNavigationBar(controllerTitle:"分类",leftBtnHidden: true, rightBtnHidden: true, rightBtnTitle: "")
     
     view.addSubview(tableview)
     
     view.addSubview(collection)
     
     loadLeftData()
 }

 override func didReceiveMemoryWarning() {
     super.didReceiveMemoryWarning()
     // Dispose of any resources that can be recreated.
 }
}
extension ZLMCategoryViewController:UITableViewDelegate,UITableViewDataSource{
 func numberOfSections(in tableView: UITableView) -> Int {
     return 1
 }
 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return self.dataArr.count
 }
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     
     let cellID = "cellId"
     
     var cell = tableView.dequeueReusableCell(withIdentifier: cellID)
     
     if cell == nil {
         cell = UITableViewCell(style: .default,reuseIdentifier:cellID)
     }
    cell?.backgroundColor = BACKGROUND_Color
     
    cell?.textLabel?.text =  self.dataArr[indexPath.row]?.appCategoryName
     
    cell?.textLabel?.textAlignment = NSTextAlignment(rawValue: 1)!
    cell?.textLabel?.font = UIFont.systemFont(ofSize: 12)
    cell?.textLabel?.textColor = RGBA(r:0.0,g:0.0,b:0.0,a:1.0)
    cell?.accessoryType = .none
    return cell!
 }
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     ///cell单选
     for i :Int in 0 ..< self.dataArr.count{
        let j:NSIndexPath = NSIndexPath.init(row: i, section: indexPath.section)
        let cell :UITableViewCell = tableView.cellForRow(at: j as IndexPath)!
         cell.backgroundColor = BACKGROUND_Color
         cell.textLabel?.textColor = .black
     }
     let cell :UITableViewCell = tableView.cellForRow(at: indexPath)!
     cell.backgroundColor = .clear
     cell.textLabel?.textColor = .red
     loadRightData(menuId: (self.leftData?.data?[indexPath.row].id)!)
 }
}
extension ZLMCategoryViewController:UICollectionViewDelegate,UICollectionViewDataSource{
 func numberOfSections(in collectionView: UICollectionView) -> Int {
     return rightDataArr.count
 }
 
 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     return (rightDataArr[section]?.categoryModels!.count)!
 }
 
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     
     let cell:ZLMCateCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLMCollectID, for: indexPath as IndexPath) as! ZLMCateCollectionViewCell
     
     cell.model = rightDataArr[indexPath.section]?.categoryModels?[indexPath.row]
 
     return cell
     
 }
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
 
 var sectionView = ZLMHeaderCollectionReusableView()
 if kind == UICollectionElementKindSectionHeader{
     
  sectionView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ZLMHeaderID, for: indexPath) as! ZLMHeaderCollectionReusableView
     sectionView.model  = rightDataArr[indexPath.section]
 }
 return sectionView
}
}
extension ZLMCategoryViewController:UICollectionViewDelegateFlowLayout{
 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
     
     let side :CGFloat = (self.collection.frame.size.width-6*8)/3.0-8.0
     return CGSize(width:side,height:side+20)
 }
 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
     
     return UIEdgeInsetsMake(0, 8, 0, 8)
 }
 //section头部高度
 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
     
     return CGSize(width:self.collection.frame.size.width,height:30)
 }
 //section尾部高度
 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
     
     return CGSize(width:self.collection.frame.size.width,height:0)
 }
}
extension ZLMCategoryViewController{
//    func loadLeftData(){
//        NetworkTools.sharedInstance.loadCateLeft { (response) in
//            //response现在就是data
//            //遍历或是直接取就好了
//            self.dataArr = response             
//        }
//    }
 func loadLeftData(){
     let url = host+"categorys/findByGrade"
     let parameter = ["grade":"1"]
     NetworkTools.sharedInstance.request(type:.GET,url: url, parameters: parameter){ (response) in
         
         self.leftData = JSONDeserializer<ZLMCategoryModel>.deserializeFrom(json: response)
         if (self.leftData?.data?.count)! > 0{
             
             self.leftData?.data?.forEach({
                 self.dataArr.append($0)
             })
             self.tableview.reloadData()
             self.tableview.selectRow(at: NSIndexPath.init(row: 0, section: 0) as IndexPath, animated: true, scrollPosition: .bottom)
             self.tableView(self.tableview, didSelectRowAt: NSIndexPath.init(row: 0, section: 0) as IndexPath)
         }
     }
 }
 func loadRightData(menuId:Int) {
     let url = host+"categorys/"+"\(menuId)"+"/childs"
     
     NetworkTools.sharedInstance.request(type:.GET,url: url){ (response) in
         self.rightData = JSONDeserializer<ZLMCategoryRightModel>.deserializeFrom(json: response)
         if self.rightData?.code == 1{
             self.rightDataArr.removeAll()
             self.rightData?.data?.categoryModelList?.forEach({
                self.rightDataArr.append($0)
             })
             self.collection.reloadData()
         }
     }

 }
 func setDataSource() {
     tableview.reloadData()
 }
}

cell中的代码就不写了,

分类.jpeg

由于是公司项目,就不方便贴上demo了,有问题可评论留言哦。
以上。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容