Search code examples
swiftxcode6fadeuitableview

Swift - Fading cells in UITableView


I'm having troubles with my UITableView in swift on Xcode 6 :

I would like my UITableView cells to fade in / out when appearing / disappearing.

I looked a lot on the web for fade animations but I didn't find what I wanted because it's based on duration animations.

I Think what I need is sort of mask based on alpha ? I'm not sur and I don't even know have to create one...

I have a UIViewController containing a tableView and some blank space (for now) upside and downside of the UITableView.

Thank's for your help !!

Best,

Anatole


Solution

  • animateWithDuration seems appropriate, since the fade in/out has a duration: the cell gradually becoming visible or invisible over time.

    Here is an example of making table cells fade-in:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        var cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    
        cell.textLabel?.text = self.items[indexPath.row]
        cell.backgroundColor = UIColor.grayColor()
        cell.alpha = 0
    
        UIView.animateWithDuration(2, animations: { cell.alpha = 1 })
    
        return cell
    }
    

    EDIT:

    This sets the cell's alpha based on their y position, which is probably closer to what you want:

    func scrollViewDidScroll(scrollView: UIScrollView) {
    
        for cell in tableView.visibleCells() as [UITableViewCell] {
    
            var point = tableView.convertPoint(cell.center, toView: tableView.superview)
            cell.alpha = ((point.y * 100) / tableView.bounds.maxY) / 100
        }
    }