mindz-eye / MYTableViewIndex

A pixel perfect replacement for UITableView section index, written in Swift
MIT License
523 stars 52 forks source link

Pin TableViewIndex to Specific Sections #10

Open AAAstorga opened 7 years ago

AAAstorga commented 7 years ago

It would be nice to have the built in feature described in the title. This is how I did it in the meantime, and here was the result. Result - TableViewIndex pinned to 3rd section pinnedindexbar

 func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let contentOffsetY = scrollView.contentOffset.y
        if scrollView == tableView && searchBar.text == "" {
            if let visibleRows = tableView.indexPathsForVisibleRows {
                let visibleSections = visibleRows.map({$0.section})
                if let allStopsIndex = sections.index(where: {$0.type == SectionType.AllStops}), let firstAllStopCellIndexPath = visibleRows.filter({$0.section == allStopsIndex && $0.row == 1}).first {
                    let secondCell = tableView.cellForRow(at: firstAllStopCellIndexPath)
                    let newYPosition = view.convert(tableViewIndexController.tableViewIndex.indexRect(), from: tableView).minY
                    if ((newYPosition * -1.0) < (secondCell?.frame.minY)! - view.bounds.midY) {
                        let offset = (secondCell?.frame.minY)! - initialTableViewIndexMidY - contentOffsetY
                        tableViewIndexController.tableViewIndex.indexOffset = .init(horizontal: 0.0, vertical: offset)
                        tableViewIndexController.setHidden(!visibleSections.contains(allStopsIndex), animated: true)
                    }
                }
            }
        }
    }