how to retrieve all visible table section header views

后端 未结 10 563
渐次进展
渐次进展 2020-12-31 04:44

is there a way to get all the section header views that are visible?

something similar to UITableView\'s visibleCells instance method..

10条回答
  •  旧时难觅i
    2020-12-31 05:08

    The solution by Benjamin Wheeler is a great Swift solution. I fixed an issue in it due to new Swift syntax, and modified it to match the .visibleCells property provided by the default UITableView implementation.

    extension UITableView {
    
        /// The table section headers that are visible in the table view. (read-only)
        ///
        /// The value of this property is an array containing UITableViewHeaderFooterView objects, each representing a visible cell in the table view.
        ///
        /// Derived From: [http://stackoverflow.com/a/31029960/5191100](http://stackoverflow.com/a/31029960/5191100)
        var visibleSectionHeaders: [UITableViewHeaderFooterView] {
            get {
                var visibleSects = [UITableViewHeaderFooterView]()
    
                for sectionIndex in indexesOfVisibleSections() {
                    if let sectionHeader = self.headerViewForSection(sectionIndex) {
                        visibleSects.append(sectionHeader)
                    }
                }
    
                return visibleSects
            }
        }
    
        private func indexesOfVisibleSections() -> Array {
            // Note: We can't just use indexPathsForVisibleRows, since it won't return index paths for empty sections.
            var visibleSectionIndexes = Array()
    
            for (var i = 0; i < self.numberOfSections; i++) {
                var headerRect: CGRect?
                // In plain style, the section headers are floating on the top,
                // so the section header is visible if any part of the section's rect is still visible.
                // In grouped style, the section headers are not floating,
                // so the section header is only visible if it's actual rect is visible.
                if (self.style == .Plain) {
                    headerRect = self.rectForSection(i)
                } else {
                    headerRect = self.rectForHeaderInSection(i)
                }
    
                if headerRect != nil {
                    // The "visible part" of the tableView is based on the content offset and the tableView's size.
                    let visiblePartOfTableView: CGRect = CGRect(
                        x: self.contentOffset.x,
                        y: self.contentOffset.y,
                        width: self.bounds.size.width,
                        height: self.bounds.size.height
                    )
    
                    if (visiblePartOfTableView.intersects(headerRect!)) {
                        visibleSectionIndexes.append(i)
                    }
                }
            }
    
            return visibleSectionIndexes
        }
    }
    

提交回复
热议问题