如何在UITableViewCell选择期间为文本标签颜色更改设置动画?

时间:2015-12-30 04:16:04

标签: swift uitableview selection tableviewcell

我试图通过创建UITableViewCell的子类来为我的表格视图单元格创建自定义选择样式。当我单击一个单元格时,我希望它能够改变颜色并淡化回原始颜色。我已经阅读了其他帖子,例如this one,但它似乎无法发挥作用。

修改:selectionStyle设置为.None

当我使用setHighlighted(_:)时,颜色不会立即改变,只有在点击持续0.5秒后才会发生。

我还使用了setSelected(_:)。颜色立即改变但不会改变。所以我在deselectRowAtIndexPath(_:)中添加了tableView(didSelectRowAtIndexPath:),但这根本不会导致任何更改。然后我尝试使用tableView.reloadRowsAtIndexPaths(_:),最后颜色发生变化并返回原始颜色。但不幸的是,它没有动画最后一部分,渐渐回归到原来的颜色。另外我注意到颜色改变后,它也会使原始颜色变暗(由tableView.reloadRowsAtIndexPaths(_:)引起)。

我放弃使用setSelected(_:)setHighlighted(_:)并尝试使用touchesBegan(_:)touchesEnded(_:)。保持简短,与上述相同......

这些是我尝试过的代码(并非全部)。

UITableViewCell的子类中:

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    label.textColor = selected ? UIColor.redColor() : UIColor.blackColor()
}

override func setHighlighted(highlighted: Bool, animated: Bool) {
    label.textColor = highlighted ? UIColor.redColor() : UIColor.blackColor()
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesBegan(touches, withEvent: event)

    label.textColor = UIColor.redColor()
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesEnded(touches, withEvent: event)

    let changeEnded = CATransition()
    changeEnded.duration = 0.5

    nameLabel.layer.addAnimation(changeEnded, forKey: nil)
    nameLabel.textColor = .blackColor()
}

在表格视图控制器中(不在一起):

tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

tableView.deselectRowAtIndexPath(indexPath, animated: true)

1 个答案:

答案 0 :(得分:4)

我设法解决了它,但它并不觉得这应该是怎么做的。为UILabel动画这样一个简单的动画是不是更简单?

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let selected = tableView.cellForRowAtIndexPath(indexPath) as! CustomViewCell

    let changeColor = CATransition(); changeColor.duration = 1

    CATransaction.begin()

    CATransaction.setCompletionBlock {
        selected.label.layer.addAnimation(changeColor, forKey: nil)
        selected.label.textColor = .blackColor()
    }

    selected.nameLabel.textColor = .redColor()

    CATransaction.commit()
}
相关问题