I need this because I need to change the background color of a section. For example, if section at the top then blue green otherwise.
I have tried many things but I am with my ideas at the end.
I need this because I need to change the background color of a section. For example, if section at the top then blue green otherwise.
I have tried many things but I am with my ideas at the end.
Try this
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Background color
view.backgroundColor = section == 0 ? [UIColor blueColor] : [UIColor greenColor];
// Another way to set the background color
// Note: does not preserve gradient effect of original header
// UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
// header.contentView.backgroundColor = [UIColor blackColor];
}
Considering top means 1st section.
Edit
If you want to change color according to scrolling and identifying which section is on top and which is not then you have to implement UIScrollViewDelegate so that you can handle scrolling delegates. You can try something like this
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
NSIndexPath *firstVisibleIndexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:0];
NSLog(@"first visible cell's section: %i, row: %i", firstVisibleIndexPath.section, firstVisibleIndexPath.row);
}
References: UIScrollViewDelegate implementation and Detecting top cell in TableView
Try this:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
NSArray* visibleCellIndexPaths = [tableView indexPathsForVisibleRows];
//Set all header views to have a blue background color.
[view setBackgroundColor:[UIColor blueColor]];
if(visibleCellIndexPaths.count > 0)
{
//Set the topmost visible section header view to have green background color.
[[tableView headerViewForSection:[visibleCellIndexPaths[0] section]] setBackgroundColor:[UIColor greenColor]];
}
}
Just check if the frame of the section header you're looking for has moved to the top.
Swift version of @faisal Ali answer
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = section == 0 ? UIColor.white : UIColor.clear
}