Swift - UITableView 中的淡入淡出单元格

Swift - Fading cells in UITableView

我在 Xcode 6 上 swift 中的 UITableView 遇到问题:

我希望我的 UITableView 单元格在出现/消失时淡入/淡出。

我在网上找了很多淡入淡出动画,但没有找到我想要的,因为它是基于持续时间动画的。

我想我需要的是一种基于 alpha 的掩码?我不是 sur,我什至不知道必须创建一个...

我有一个 UIViewController,其中包含一个 tableView 和一些空白 space(目前)UITableView 的优点和缺点。

感谢您的帮助!!

最佳,

阿纳托尔

animateWithDuration 似乎是合适的,因为淡入淡出 in/out 有持续时间:随着时间的推移,单元格逐渐变得可见或不可见。

这是使 table 个单元格淡入的示例:

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
}

编辑:

这会根据它们的 y 位置设置单元格的 alpha,这可能更接近您想要的:

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
    }
}

我一直在寻找同样的东西,最后我自己做了,我想我会分享它:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let cellCount = tableView.visibleCells.count
    let alphaInterval:CGFloat = 1.0 / CGFloat(cellCount / 2)

    for (index,cell) in (tableView.visibleCells as [UITableViewCell]).enumerated() {

        if index < cellCount / 2 {
            cell.alpha = CGFloat(index) * alphaInterval
        } else {
            cell.alpha = CGFloat(cellCount - index) * (alphaInterval)
        }
    }
}

这里是单元格:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    cell.textLabel?.text = countries[indexPath.row].uppercased()
    cell.textLabel?.textColor = .white
    cell.backgroundColor = .clear
    cell.alpha = 0.25

    UIView.animate(withDuration: 0.5, animations: {
        cell.alpha = 1 
    })

    return cell
}

最终看起来像这样: