Skip to content

Instantly share code, notes, and snippets.

@eonist
Created May 21, 2023 13:31
Show Gist options
  • Save eonist/22099d4f4cfd4b5490bd1c239cddc205 to your computer and use it in GitHub Desktop.
Save eonist/22099d4f4cfd4b5490bd1c239cddc205 to your computer and use it in GitHub Desktop.
UITableViewDelegate extension
/**
* Table extensions
* - Fixme: ⚠️️ deprecate these, not in use anymore. move to gist or something?
*/
extension UITableViewDataSource where Self: UITableView {
/**
* Returns all IndexPath's in a table
* ## Examples:
* table.indexPaths.forEach {
* selectRow(at: $0, animated: true, scrollPosition: .none) // selects all cells
* }
*/
public var indexPaths: [IndexPath] {
(0..<self.numberOfSections).indices.map { (sectionIndex: Int) -> [IndexPath] in
(0..<self.numberOfRows(inSection: sectionIndex)).indices.compactMap { (rowIndex: Int) -> IndexPath? in
IndexPath(row: rowIndex, section: sectionIndex)
}
}.flatMap { $0 }
}
/**
* Returns rowCount in table (sections * rows)
* - Fixme: ⚠️️ move to commoncell?, its already there, just make it public etc
*/
public var rowCount: Int {
(0..<numberOfSections).indices.map { numberOfRows(inSection: $0) }.reduce(0, +)
}
}
/**
* UITableViewDelegate extension
*/
extension UITableViewDelegate where Self: UITableView {
/**
* Returns total height of all rows
* - Important: ⚠️️ In the heightForRowAt class, don't use cellForRow, as the cell isn't made yet, probably shouldn't put cellForRow in that method anyways
* - Fixme: ⚠️️ Use .first instead of contains check? I think contains is correct actually?
*/
public func totalRowHeight(exceptions: [IndexPath]) -> CGFloat {
(0..<self.numberOfSections).indices.flatMap { sectionIdx in
(0..<self.numberOfRows(inSection: sectionIdx)).indices.filter { !exceptions.contains(.init(row: $0, section: sectionIdx)) }.map { rowIdx in
self.tableView!(self, heightForRowAt: .init(row: rowIdx, section: sectionIdx))
}
}.reduce(0, +)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment