切换颜色动画
最初的想法
两个UIView直接切换,上代码
let aView = UIView() let bView = UIView() aView.frame = CGRect(x: 100, y: 300, width: 100, height: 100) aView.alpha = 1 aView.backgroundColor = .red view.addSubview(aView) bView.frame = CGRect(x: 100, y: 300, width: 100, height: 100) bView.alpha = 0 bView.backgroundColor = .orange view.addSubview(bView) func switchView(type: Int) { if type == 0 { UIView.animate(withDuration: 0.3) { self.aView.alpha = 0 self.bView.alpha = 1 } completion: { finished in if finished { self.aView.alpha = 0 self.bView.alpha = 1 } } } else { UIView.animate(withDuration: 0.3) { self.aView.alpha = 1 self.bView.alpha = 0 } completion: { finished in if finished { self.aView.alpha = 1 self.bView.alpha = 0 } } } }
但是效果不是很如意,有些闪动
修改之后的方案
通过两个CALayer做动画,当然如果是渐变,用CAGradientLayer也可以
let tView = UIView() let layer = CALayer() tView.frame = CGRect(x: 100, y: 100, width: 100, height: 100) view.addSubview(tView) layer.frame = tView.bounds layer.backgroundColor = UIColor.red.cgColor tView.layer.addSublayer(layer) func switchView(type: Int) {
let duration: CFTimeInterval = 0.3
let colorChangeAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorChangeAnimation.duration = duration
colorChangeAnimation.fillMode = .forwards
colorChangeAnimation.isRemovedOnCompletion = false if type == 0 { colorChangeAnimation.toValue = UIColor.orange.cgColor layer.removeAnimation(forKey: "colorChangeAnimationa") layer.add(colorChangeAnimation, forKey: "colorChangeAnimationa") } else { colorChangeAnimation.toValue = UIColor.red.cgColor layer.removeAnimation(forKey: "colorChangeAnimationb") layer.add(colorChangeAnimation, forKey: "colorChangeAnimationb") } }
两种方案对比视频
能看出来下面比闪动厉害
总结
用CALayer做动画效果更好。如果只是单纯改变背景色,用下面代码实现更加方便
let gView = UIView() gView.frame = CGRect(x: 100, y: 500, width: 100, height: 100) gView.backgroundColor = .red view.addSubview(gView) func changeColor(color: UIColor) { UIView.animate(withDuration: 3) { self.gView.backgroundColor = color } }
分类:
iOS
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理