Reputation: 7022
I've got a UITableView
in a UIViewController
, as well as a filter button. I hide the filter button when the user starts to scroll down the list. I want to then show the filter button when the second cell (index 1
) is visible. However, I can't get this desired effect, I can only get it to appear when it reaches the top. Here is my code for when it reaches the top (I then show the filter button again).
//determines when the tableview was scrolled
-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
CGPoint currentOffset = scrollView.contentOffset;
//tableview is scrolled down
if (currentOffset.y > self.lastContentOffset.y)
{
//if the showFilter button is visible i.e alpha is greater than 0
if (self.showFilter.alpha==1.0) {
[UIView animateWithDuration:1 animations:^{
//hide show filter button
self.showFilter.alpha=0.0;
//I also adjust the frames of a tableview here
}];
}
}
//determines if it is scrolled back to the top
if (self.showFilter.alpha==0.0 && currentOffset.y==0) {
[UIView animateWithDuration:0.3 animations:^{
//show filter button
self.showFilter.alpha=1.0;
//i also adjust the frames of the tableview here
}];
}
self.lastContentOffset = currentOffset;
}
I have also tried:
if (self.showFilter.alpha==0.0 && currentOffset.y<160)
But it doesn't work to the desired effect as the tableview jumps off the screen. Is there another way to get this desired effect?
Upvotes: 1
Views: 1365
Reputation: 5029
A previous answer suggested that you should check if the cell is visible every time the table view scrolls (in scrollViewDidScroll:
). However, you should not do this. That approach could affect the performance of your table view since a check must be performed every single time the table view scrolls.
Instead, you only need to check every time a new cell will become visible by implementing this UITableViewDelegate
method:
- (void)tableView:(nonnull UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
if ([indexPath isEqual:[NSIndexPath indexPathForRow:1 inSection:0]]) {
// perform action
}
}
Prior to Swift 3 you would write the following:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath == NSIndexPath(forRow: 1, inSection: 0) {
// perform action
}
}
In Swift 3 or greater you would write the following:
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath == IndexPath(row: 1, section: 0) {
// perform action
}
}
In either case don't forget to set your UIViewController
subclass as the delegate
of the UITableView
.
Upvotes: 3