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