如果/ else,简化UIView动画

时间:2017-08-23 17:56:39

标签: swift swift3 uiview uiviewanimation

iOS UIKit库中的许多回调和方法都有一个animated布尔值,表示动作是应该动画还是只是设置。

这种方法就是这样一个例子:

UITableViewCell.setSelected(_ selected: Bool, animated: Bool)

假设我想在选择时更改textLabel文本颜色和单元格的背景颜色。我目前正在做这样的事情:

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

    let bgColor = !selected ? UIColor.clear : UIColor.blue
    let textColor = !selected ? UIColor.black : UIColor.white             

    if !animated {
        self.textLabel?.textColor = textColor
        self.backgroundColor = bgColor
    } else {
        UIView.animate(withDuration: 0.1) {
            self.textLabel?.textColor = textColor
            self.backgroundColor = bgColor
        }            
    }        
}

很简单,我计算出新的颜色值,然后应用它们。

这里令人沮丧的部分是我必须检查我们是否正在制作动画,以及我们是否将制定者包装在动画块中。这感觉非常难看,如果你做的不仅仅是改变背景颜色,那就更糟了。

我确信其他人已经优雅地解决了这个问题,所以我想知道你们(和女士们)是怎么做到的?

1 个答案:

答案 0 :(得分:0)

制作一个func来处理你想要改变的东西,例如,

    func updateTheme(selected: Bool) {
        self.textLabel?.textColor = !selected ? UIColor.clear : UIColor.blue
        self.backgroundColor = !selected ? UIColor.black : UIColor.white
    }

然后在你的主要功能中调用它

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        UIView.animate(withDuration: selected ? 0.1 : 0) {
            self.updateTheme(selected: selected)
        }        
    }

或者

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

    if !animated {
        updateTheme(selected: selected)
    } else {
        UIView.animate(withDuration: 0.1) {
            self.updateTheme(selected: selected)
        }            
    }        
}