Here’s today’s entry for the ‘Most Complicated Way To Do Something Easy’ sweepstakes:
Q: “I am trying to fade out he top/ bottom cells in a tableview. How do I achieve this effect?”
A: Adding Fading Gradients to UITableView
… have the part for the table view “cut out” in the image, i.e. have the center portion be Alpha 0 and the top and bottom would be an alpha gradient from 100% to 0%.
A designer versed with Photoshop could easily create something like this for you. Then you put this imageView on top of your table view, size the table view to fit inside the border. Finally you will want to make sure that userInteraction is disabled on the imageView, because otherwise no touches would be reaching the table view…
Yep, we’ve done exactly that several times, and used the same technique for custom-looking UIPickerView constructions and the like. That wouldn’t be worth bothering to mention, would it now? No, no it would not. But a lesson in how to spend a few hundred lines of code accomplishing the same task as taking ten seconds to drop on a PNG, well that’s worth a post just in case you ever have a hard problem that knowledge of CALayer masking would be actually needed to solve, yes?
While this solution is simple it does not satisfy me personally. As developer I want to achieve such an effect entirely in code because then it has the added advantage of being independent or resolution or interface orientation.
The first thing we’ll try is to mask the layer of the table view. On iOS each UIView has a CALayer that takes care of the actual drawing. And each CALayer has a mask property where you can set another layer to mask out parts of the host layer…
… If we stopped here then you would get the gradients, but they would move together with the contents of the table view. Luckily table views are UIScrollView child classes and thus you can also implement the UIScrollViewDelegate methods. We are using the one that fires on each movement to adjust the position of the masking layer…
… There’s another problem that only becomes apparent if you start scrolling and the vertical scroll bar shows: it is also affected by the mask which you probably don’t want because it looks weird. So instead of actually use the mask for the regular layer masking we add it as a sublayer…
Whilst our personal standards of satisfaction tend to place a vastly higher value on expediency and efficiency of client contentment … hey, there’s nothing more expedient and efficient than picking up tips from those of a more recherché inclination!
UPDATES:
Here’s FadingTextView for iOS which uses masking gradient views for this kind of thing.
OCT