Skip to content

Instantly share code, notes, and snippets.

@gabrieltheodoropoulos
Last active January 4, 2024 08:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrieltheodoropoulos/20c452aa61fc9e4a1a3d8b7a36787bc2 to your computer and use it in GitHub Desktop.
Save gabrieltheodoropoulos/20c452aa61fc9e4a1a3d8b7a36787bc2 to your computer and use it in GitHub Desktop.
iOS/Swift Tip - Add a sticky and stretchy top cell to your UITableView
// For more information, visit:
// https://gtiapps.com/?p=4482
// It is pressumed that you have added a table view (UITableView) to your view controller,
// and that you have set the view controller as the delegate of the tableview (tableView.delegate = self).
// Two different approaches are provided:
// Approach #1
// Implement the following scroll view delegate method:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0.0 {
if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) {
cell.frame.origin.y = scrollView.contentOffset.y
let originalHeight: CGFloat = 280.0
cell.frame.size.height = originalHeight + scrollView.contentOffset.y * (-1.0)
}
}
}
// Approach #2:
// Declare the following property in your class:
var lastContentOffset = CGPoint.zero
// Implement the following scroll view delegate method:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0.0 {
if let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) {
let deltaY = CGFloat(fabsf(Float(scrollView.contentOffset.y)) - fabsf(Float(lastContentOffset.y)))
cell.frame = CGRect(x: 0.0, y: scrollView.contentOffset.y, width: cell.frame.size.width, height: cell.frame.size.height + deltaY)
lastContentOffset = scrollView.contentOffset
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment