Last active
January 4, 2024 08:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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