tableView與collectionView聯動功能的實現(左側大分類,右側小分類)

protocol TableWithCollectionViewDelegate: NSObjectProtocol {
    func collectionView(didSelectItemAt indexPath: IndexPath)
}

class TableWithCollectionView: UIView {
    weak var delegate: TableWithCollectionViewDelegate?
    var leftModels: [String] = []{
        didSet{
            tableView.reloadData()
            tableView.selectRow(at: IndexPath(row: currentIndex, section: 0), animated: false, scrollPosition: .none)
        }
    }
    var rightModels: [[String]] = []{
        didSet{
            collectionView.reloadData()
        }
    }
    
    
    private var currentIndex: Int = 0 //tableView當前選中的index
    private var sectionInsets: CGFloat = 10~
    private var tableView: BaseTableView!
    private var collectionView: UICollectionView!
    //右側collectionView當前是否正在向下滾動(即true表示手指向上滑動,查看下面內容)
    private var collectionViewIsScrollDown = true
    //右側collectionView垂直偏移量
    private var collectionViewLastOffsetY : CGFloat = 0.0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setUI()
    }
}
extension TableWithCollectionView{
    private func setUI(){
        setTableView()
        setCollectionView()
    }
    private func setTableView(){
        tableView = BaseTableView()
        tableView.backgroundColor = .cWhite
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isNoDate = false
        tableView.bounces = false
        tableView.register(LTitleCell.self, forCellReuseIdentifier: LTitleCell.cellID)
        self.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.leading.bottom.equalToSuperview()
            make.width.equalTo(88~)
        }
    }
    private func setCollectionView(){
        let layout = JJCollectionViewRoundFlowLayout_Swift()
        layout.isCalculateHeader = false
        layout.isCalculateFooter = false
        layout.sectionHeadersPinToVisibleBounds = true
        layout.scrollDirection = .vertical
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.contentInsetAdjustmentBehavior = .never
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.bounces = false
        collectionView.backgroundColor = .bgColor2
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(RCollectionCell.self, forCellWithReuseIdentifier: RCollectionCell.cellID)
        collectionView.register(RCollectionSectionHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: RCollectionSectionHeader.cellID)
        collectionView.register(RCollectionSectionFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: RCollectionSectionFooter.cellID)
        self.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.bottom.equalTo(tableView)
            make.trailing.equalToSuperview().inset(10~)
            make.leading.equalTo(tableView.snp.trailing).offset(10~)
        }
    }
}

//MARK: -UITableView
extension TableWithCollectionView: UITableViewDelegate, UITableViewDataSource{
    //將右側colletionView的指定分區自動滾動到最頂端
    func collectionViewScrollToTop(section: Int, animated: Bool) {
        let rectY = collectionViewHeaderFrame(section: section)
        let topOfHeader = CGPoint(x: 0, y: rectY - collectionView.contentInset.top)
        collectionView.setContentOffset(topOfHeader, animated: animated)
    }
    //獲取colletionView的指定分區頭的高度
    func collectionViewHeaderFrame(section: Int) -> CGFloat {
        let indexPath = IndexPath(item: 0, section: section)
        let firstCell = collectionView.collectionViewLayout.layoutAttributesForItem(at: indexPath)
        let attributes = collectionView.collectionViewLayout
            .layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath)
        guard let yForFirstCell = firstCell?.frame.minY else {
            return .zero
        }
        guard let heightForHeader = attributes?.frame.height else {
            return .zero
        }
        return yForFirstCell - heightForHeader - sectionInsets
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //右側collection自動滾動到對應的分區
        collectionViewScrollToTop(section: indexPath.row, animated: true)
        currentIndex = indexPath.row
        tableView.reloadData()
        tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        leftModels.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: LTitleCell.cellID, for: indexPath) as!
        LTitleCell
        cell.title = leftModels[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let cell = cell as! LTitleCell
        switch indexPath.row {
        case currentIndex - 1:
            cell.bgView.layer.cornerRadius = 5~
            cell.bgView.layer.maskedCorners = CACornerMask(rawValue: CACornerMask.layerMaxXMaxYCorner.rawValue)
        case currentIndex + 1:
            cell.bgView.layer.cornerRadius = 5~
            cell.bgView.layer.maskedCorners = CACornerMask(rawValue: CACornerMask.layerMaxXMinYCorner.rawValue)
        default:
            cell.bgView.layer.cornerRadius = 0
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        50~
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        UIView()
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        10~
    }
}

//MARK: -UICollectionView
extension TableWithCollectionView: UICollectionViewDelegate, UICollectionViewDataSource, JJCollectionViewDelegateRoundFlowLayout_Swift{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        delegate?.collectionView(didSelectItemAt: indexPath)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        let model = JJCollectionViewRoundConfigModel_Swift.init()
        model.backgroundColor = UIColor.cWhite
        model.cornerRadius = 10~
        return model
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        rightModels.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        rightModels[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let item = collectionView.dequeueReusableCell(withReuseIdentifier: RCollectionCell.cellID, for: indexPath) as! RCollectionCell
        item.model = rightModels[indexPath.section][indexPath.item]
        return item
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: RCollectionSectionHeader.cellID, for: indexPath) as! RCollectionSectionHeader
            //設置分組標題
            header.titleLabel.text = leftModels[indexPath.section]
            return header
        }else {
            return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: RCollectionSectionFooter.cellID, for: indexPath) as! RCollectionSectionFooter
        }
    }
    
    //返回分組頭大小
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: 40~)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: section == collectionView.numberOfSections - 1 ? 10~ : 0.01)
    }
    
    //返回單元格大小
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        let itemWidth = (collectionView.bounds.width - 20~) / 3
        let itemHeight = itemWidth / 3 * 4
        return CGSize(width: itemWidth, height: itemHeight)
    }
    
    //每個分組的內邊距
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: sectionInsets, left: sectionInsets, bottom: sectionInsets, right: sectionInsets)
    }
    
    //單元格的行間距
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 1.0
    }
    
    //單元格橫向的最小間距
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }
    //分區頭即將要顯示時調用
    func collectionView(_ collectionView: UICollectionView,
                        willDisplaySupplementaryView view: UICollectionReusableView,
                        forElementKind elementKind: String, at indexPath: IndexPath) {
        //如果是由用戶手動滑動屏幕造成的向上滾動,那么左側表格自動選中該分區對應的分類
        if !collectionViewIsScrollDown
            && (collectionView.isDragging || collectionView.isDecelerating) {
            currentIndex = indexPath.section
            tableView.reloadData()
            tableView.selectRow(at: IndexPath(row: currentIndex, section: 0),
                                animated: true, scrollPosition: .top)
        }
    }
    //分區頭即將要消失時調用
    func collectionView(_ collectionView: UICollectionView,
                        didEndDisplayingSupplementaryView view: UICollectionReusableView,
                        forElementOfKind elementKind: String, at indexPath: IndexPath) {
        //如果是由用戶手動滑動屏幕造成的向下滾動,那么左側表格自動選中該分區對應的下一個分區的分類
        if collectionViewIsScrollDown && (collectionView.isDragging || collectionView.isDecelerating) {
            currentIndex = indexPath.section + 1
            tableView.reloadData()
            tableView.selectRow(at: IndexPath(row: currentIndex, section: 0), animated: true, scrollPosition: .top)
        }
    }
    
    //視圖滾動時觸發(主要用于記錄當前collectionView是向上還是向下滾動)
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if collectionView == scrollView {
            collectionViewIsScrollDown = collectionViewLastOffsetY < scrollView.contentOffset.y
            collectionViewLastOffsetY = scrollView.contentOffset.y
        }
    }
}

其中JJCollectionViewDelegateRoundFlowLayout_Swift是用于設置UIcollectionView的section底色,圓角

IMG_3992.PNG
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,725評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,695評論 2 370

推薦閱讀更多精彩內容