32

I want the header to mask the cells, but not the background.

I have a UITableView with transparent headers and cells similar to Apple's Notification Center (when you swipe down on the status bar on your iPhone). I can't figure out how to mask the cells so they don't show up underneath the header when it scrolls.

I've tried changing the contentInsets of the tableview, and I've tried changing the frame of the header View to a negative origin.

4
  • Are you talking about table headers, or section headers?
    – RonLugge
    Aug 26, 2012 at 3:36
  • @RonLugge He's talking about section headers. You can clearly see what he means when you open the notification center as he described.
    – Mazyod
    Aug 26, 2012 at 4:16
  • 1
    I wonder if that is a transparent header (in Notification Center), or just one that has the same background as the rest of the screen? Could you solve your problem by doing that, or is your background to complicated for that to work?
    – rdelmar
    Aug 26, 2012 at 5:18
  • @rdelmar The header in the Notification Center is transparent when it moves, and I'm guessing it doesn't change depending on position. My TableView style is pretty similar to the Apple Notification Center, it has a complex background and multiple sections that rely on shadows and highlights to add depth. Downgrading the graphics to an opaque header would be my last resort. Aug 26, 2012 at 9:47

11 Answers 11

68

Try to make a subclass of UITableviewCell and add these methods

- (void)maskCellFromTop:(CGFloat)margin {
    self.layer.mask = [self visibilityMaskWithLocation:margin/self.frame.size.height];
    self.layer.masksToBounds = YES;
}

- (CAGradientLayer *)visibilityMaskWithLocation:(CGFloat)location {
    CAGradientLayer *mask = [CAGradientLayer layer];
    mask.frame = self.bounds;
    mask.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:1 alpha:0] CGColor], (id)[[UIColor colorWithWhite:1 alpha:1] CGColor], nil];
    mask.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:location], [NSNumber numberWithFloat:location], nil];
    return mask;
}

and add this delegate method in UITableView

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    for (iNotifyTableViewCell *cell in self.visibleCells) {
        CGFloat hiddenFrameHeight = scrollView.contentOffset.y + [iNotifyHeaderView height] - cell.frame.origin.y;
        if (hiddenFrameHeight >= 0 || hiddenFrameHeight <= cell.frame.size.height) {
            [cell maskCellFromTop:hiddenFrameHeight];
        }
    }
}

*Note that [iNotifyHeaderView height] is the height of the HeaderView. and use #import <QuartzCore/QuartzCore.h> for the custom cell.

16
  • Thanks! Works like charm! I was struggling with this all day. I can't believe I had to link the QuartzCore.framework just for this. However I want to replicate your code for footers too but I can't get how does the mask work, can you explain a little?
    – htafoya
    Mar 8, 2013 at 5:01
  • in iOS mask is kinda different, White portion shows the part and transparent doesn't. So this code makes a mask transparent at the top with the same height as header but rest is white, so the cell portion is visible, but the part behind the header is hidden. :) Mar 9, 2013 at 0:35
  • Oh ok, however at the end I didn't use it because it made some glitches when device was rotated and the data was reloaded.
    – htafoya
    Mar 13, 2013 at 23:29
  • 5
    @AlexMarkman thank you, works perfectly. I would add the top of the tableView's contentInset property to the hiddenFrameHeight you are calculating to account for the automatic inset that iOS 7 adds to scrollViews, and to any space added by refresh controls etc: CGFloat hiddenFrameHeight = scrollView.contentOffset.y + [iNotifyHeaderView height] - cell.frame.origin.y + scrollView.contentInset.top;
    – boliva
    Feb 27, 2014 at 13:41
  • 4
    I have also added this code to UITableViewCell's maskCellFromTop: method to increase performance (removing mask if margin is not appropriate for current cell) if (margin > 0) { self.layer.mask = [self visibilityMaskWithLocation:margin/self.frame.size.height]; self.layer.masksToBounds = YES; } else { self.layer.mask = nil; } Aug 28, 2014 at 14:13
18

A little edit on Alex Markman's answer, where you could skip creating a subclass for an UITableViewCell. Benefit of this approach is that you can use it for multiple different UITableViewCells.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    for (UITableViewCell *cell in self.tableView.visibleCells) {
        CGFloat hiddenFrameHeight = scrollView.contentOffset.y + self.navigationController.navigationBar.frame.size.height - cell.frame.origin.y;
        if (hiddenFrameHeight >= 0 || hiddenFrameHeight <= cell.frame.size.height) {
            [self maskCell:cell fromTopWithMargin:hiddenFrameHeight];
        }
    }
}

- (void)maskCell:(UITableViewCell *)cell fromTopWithMargin:(CGFloat)margin
{
    cell.layer.mask = [self visibilityMaskForCell:cell withLocation:margin/cell.frame.size.height];
    cell.layer.masksToBounds = YES;
}

- (CAGradientLayer *)visibilityMaskForCell:(UITableViewCell *)cell withLocation:(CGFloat)location
{
    CAGradientLayer *mask = [CAGradientLayer layer];
    mask.frame = cell.bounds;
    mask.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:1 alpha:0] CGColor], (id)[[UIColor colorWithWhite:1 alpha:1] CGColor], nil];
    mask.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:location], [NSNumber numberWithFloat:location], nil];
    return mask;
}
2
  • 1
    Love this. worked like a charm. I like that I didn't have to subclass anything. I only had to modify self.navigationController.navigationBar.frame.size.height to use the height of my table header. -rrh Oct 1, 2015 at 19:13
  • This is a good solution, but there is an issue. If you use some sort of paging in your table view when loading data, there is an issue with the mask, i.e. it hides the bottom part of the last cell when the tablefooterview which shows the loading indicator for the paging igets hidden.
    – damjandd
    Feb 6, 2017 at 10:23
12

@Alex Markman - your answer is great and was very usefull for me, but I found that when you're scrolling on retina devices, the cells do not scroll smoothly. I found that it is caused by layer's locations parameter during the rendering process:

mask.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:location];

I slightly modified your code. Maybe someone will find it useful:

- (void)maskCellFromTop:(CGFloat)margin
{
    self.layer.mask = [self visibilityMaskFromLocation:margin];
    self.layer.masksToBounds = YES;
}

- (CAGradientLayer *)visibilityMaskFromLocation:(CGFloat)location
{
    CAGradientLayer *mask = [CAGradientLayer layer];
    mask.frame = CGRectMake(
                            self.bounds.origin.x,
                            location+self.bounds.origin.y,
                            self.bounds.size.width,
                            self.bounds.size.height-location);
    mask.colors = @[
                    (id)[[UIColor colorWithWhite:1 alpha:1] CGColor],
                    (id)[[UIColor colorWithWhite:1 alpha:1] CGColor]
                    ];
    return mask;
}
6

Swift version

func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    for cell in tableView.visibleCells {
        let hiddenFrameHeight = scrollView.contentOffset.y + navigationController!.navigationBar.frame.size.height - cell.frame.origin.y
        if (hiddenFrameHeight >= 0 || hiddenFrameHeight <= cell.frame.size.height) {
            maskCell(cell: cell, margin: Float(hiddenFrameHeight))
        }
    }
}

func maskCell(cell: UITableViewCell, margin: Float) {
    cell.layer.mask = visibilityMaskForCell(cell: cell, location: (margin / Float(cell.frame.size.height) ))
    cell.layer.masksToBounds = true
}

func visibilityMaskForCell(cell: UITableViewCell, location: Float) -> CAGradientLayer {
    let mask = CAGradientLayer()
    mask.frame = cell.bounds
    mask.colors = [UIColor(white: 1, alpha: 0).cgColor, UIColor(white: 1, alpha: 1).cgColor]
    mask.locations = [NSNumber(value: location), NSNumber(value: location)]
    return mask;
}
3
  • It works fine, yet I've different tableview at the bottom of the same ViewController and when I scroll the second tableview, the cells of the first tableview disappear too! what is the problem ?
    – MarcoPolo
    Sep 25, 2019 at 10:20
  • On iOS 14 this is not working properly while rotating the device to vertical and back. It cuts all cells on the side. Seems like something with the coordinate system. Oct 23, 2020 at 5:16
  • It is working fine with the fixed table view cell height, but the view is cropping for the dynamic cell height until scroll the table view. can anyone help with this? Sep 6, 2022 at 13:46
5

Clean Swift 3 Version:

extension YourViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        for cell in tableView.visibleCells {
            let hiddenFrameHeight = scrollView.contentOffset.y + navigationController!.navigationBar.frame.size.height - cell.frame.origin.y
            if (hiddenFrameHeight >= 0 || hiddenFrameHeight <= cell.frame.size.height) {
                if let customCell = cell as? CustomCell {
                    customCell.maskCell(fromTop: hiddenFrameHeight)
                }
            }
        }
    }
}

class CustomCell: UITableViewCell {
    public func maskCell(fromTop margin: CGFloat) {
        layer.mask = visibilityMask(withLocation: margin / frame.size.height)
        layer.masksToBounds = true
    }

    private func visibilityMask(withLocation location: CGFloat) -> CAGradientLayer {
        let mask = CAGradientLayer()
        mask.frame = bounds
        mask.colors = [UIColor.white.withAlphaComponent(0).cgColor, UIColor.white.cgColor]
        let num = location as NSNumber
        mask.locations = [num, num]
        return mask
    }
}

I just used this and it works like a charm. I want to thank everyone in the post! Up votes all around!

1
  • It works fine, yet I've different tableview at the bottom of the same ViewController and when I scroll the second tableview, the cells of the first tableview disappear too! what is the problem ?
    – MarcoPolo
    Sep 25, 2019 at 10:20
0

I have two possible solutions, no code - just the idea:

  1. not generic, should work with the settup/design apple uses at the Notification Center.

Make the Section-Header opaque, 'clone' the background-pattern of the table as background of the section-Header. Position the background-pattern depending on the section-header offset.


  1. genereic, but probably more performance problems. Should work fine with few cells.

Add a Alpha Mask to all cell-layers. Move the Alpha Mask depending on the cell-position.


(use scrollViewDidScroll delegate method to maintain the background-pattern / Alpha-Mask offset).

0

I ended up setting the height of the section header to its minimum, and overriding UITableView's layoutSubviews to place the header on the tableView's superview, adjusting the frame's origin upward by its height.

2
  • Not the answer for the question being made.
    – nmdias
    Jul 25, 2013 at 20:52
  • The other answers were better. This post is an OP just being selfish with the correct answer.
    – Sethmr
    Mar 18, 2017 at 12:52
0

The Swift 3 version didn't work for me because I added the UITableViewController as a subview. So I had to make some changes in the extension of the scrollview.

This should also work with UITableViewController that have been pushed from another ViewController (Note: not tested)

extension NavNotitionTableViewController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    for cell in tableView.visibleCells {

        let calculatedY = cell.frame.origin.y - scrollView.contentOffset.y;
        if let customCell = cell as? NavNotitionTableViewCell {

            if(calculatedY < 44 && calculatedY > 0){
                let hideAmount = 44 - calculatedY;

                if let customCell = cell as? NavNotitionTableViewCell {
                    customCell.maskCell(fromTop: hideAmount)
                }
            }else if (calculatedY > 0){
                //All other cells
                customCell.maskCell(fromTop: 0)
            }else if (calculatedY < 0){
                customCell.maskCell(fromTop: cell.frame.height);
            }
        }
    }
}
}

In this example, I first get the frame Y origin of the cell and distract the scollViews contentOffsetY.

The height of my custom section is 44. So I define the hideAmount value for the mask.

The Cell functions are untouched:

public func maskCell(fromTop margin: CGFloat) {
    layer.mask = visibilityMask(withLocation: margin / frame.size.height)
    layer.masksToBounds = true
}

private func visibilityMask(withLocation location: CGFloat) -> CAGradientLayer {
    let mask = CAGradientLayer()
    mask.frame = bounds
    mask.colors = [UIColor.white.withAlphaComponent(0).cgColor, UIColor.white.cgColor]
    let num = location as NSNumber
    mask.locations = [num, num]
    return mask
}
0

This wouldn't work if you wanted to show content behind your table view, but, since I'm only trying to create rounded headers with a plain solid colour background behind them, what solved it for me was mimicking transparency by setting the background colour of the header's background view to the background colour of the table view (or the first parent view with an opaque background).

0
class YourViewController {
   func scrollViewDidScroll(_ scrollView: UIScrollView) {
        for cell in tableView.visibleCells {
            // if tableView is under navigationbar, set `systemTopInset`
            cell.sectionHeaderMask(delegate: self, systemTopInset: self.navigationController?.navigationBar.frame.height ?? 0)
        }
    }
}
public extension UITableViewCell {
    func sectionHeaderMask<T: UITableViewDelegate>(delegate: T, systemTopInset: CGFloat = 0) {
        guard let tableView = self.superview as? UITableView else { return }
        guard let indexPath = tableView.indexPath(for: self) else { return }
        guard let heightForHeader = delegate.tableView?(tableView, heightForHeaderInSection: indexPath.section) else { return }
        let hiddenFrameHeight = tableView.contentOffset.y - self.frame.origin.y + heightForHeader + tableView.contentInset.top + systemTopInset
        if hiddenFrameHeight >= 0 || hiddenFrameHeight <= self.frame.size.height {
            mask(margin: Float(hiddenFrameHeight))
        }
    }

    private func mask(margin: Float) {
        layer.mask = visibilityMask(location: (margin / Float(frame.size.height) ))
        layer.masksToBounds = true
    }

    private func visibilityMask(location: Float) -> CAGradientLayer {
        let mask = CAGradientLayer()
        mask.frame = self.bounds
        mask.colors = [UIColor(white: 1, alpha: 0).cgColor, UIColor(white: 1, alpha: 1).cgColor]
        mask.locations = [NSNumber(value: location), NSNumber(value: location)]
        return mask
    }
}
-3

Or, if all you need is for your UI to look nice, you could

change your table view to not have floating section headers

In two quick and easy steps (iOS 6):

  1. Change your UITableView style to UITableViewStyleGrouped. (You can do this from Storyboard/NIB, or via code.)

  2. Next, set your tableview's background view to a empty view like so [in either a method such as viewDidAppear or even in the cellForRow method (though I would prefer the former)].

yourTableView.backgroundView = [[UIView alloc] initWithFrame:listTableView.bounds];

Voila, now you have your table view - but without the floating section headers. Your section headers now scroll along with the cells and your messy UI problems are solved!

Do try this out and let me know how it goes. Happy coding :)

EDIT: for iOS 7, simply change the table view style to 'UITableViewStyleGrouped' and change the view's tint color to 'clear color'.

1
  • While this answer «works» I don't think it addresses what the OP was asking. i think the idea was to keep the header visible but the cells underneath without a transparent header
    – esttorhe
    Jan 29, 2016 at 5:00

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.