gpt4 book ai didi

ios - 实现 `backgroundColor` 的 `UIView` 的动画 `drawRect`

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:18 26 4
gpt4 key购买 nike

我有一个自定义 UIView,我想为其 backgroundColor 属性设置动画。这是 animatable property UIView 的。

这是代码:

class ETTimerUIView: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// other methods
func flashBg() {
UIView.animateWithDuration( 1.0, animations: {
self.backgroundColor = UIColor.colorYellow()
})
}
override func drawRect() {
// Something related to a timer I'm rendering
}

这段代码导致动画跳过并且颜色立即改变:

self.backgroundColor = UIColor.colorYellow() // Changes immediately to yellow

如果我为 alpha 设置动画,这会按预期在一秒内从 1 到 0 设置动画:

self.alpha = 0 // animates

在这种情况下如何设置背景颜色变化的动画?

我想我需要创建一个单独的 View ——它应该放在同一个 View Controller 的 Storyboard中吗?以编程方式创建?

抱歉,我是 iOS 和 Swift 的新手。

最佳答案

当我尝试时它确实不起作用,我有一个相关的问题,将 layoutIfNeeded() 方法放在动画中有效并使 View 平滑动画(move button towards target using constraints, no reaction?)。但是在这种情况下,使用 backgroundColor 是行不通的。如果有人知道答案,我会很想知道。

但如果您现在需要一个解决方案,您可以创建一个仅用作容器的 UIView(以编程方式或通过 Storyboard)。然后在里面添加 2 个 View :一个在上面,一个在下面,与容器具有相同的框架。而且你只改变顶 View 的 alpha,让用户看到后面的 View :

class MyView : UIView {
var top : UIView!

override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.blueColor()

top = UIView(frame: CGRectMake(0,0, self.frame.width, self.frame.height))
top.backgroundColor = UIColor.yellowColor()
self.addSubview(top)
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let sub = UIView(frame: CGRectMake(0,0, self.frame.width, self.frame.height))
sub.backgroundColor = UIColor.purpleColor()
self.sendSubviewToBack(sub)
UIView.animateWithDuration(1, animations: { () -> Void in
self.top.alpha = 0
}) { (success) -> Void in
println("anim finished")
}
}
}

关于ios - 实现 `backgroundColor` 的 `UIView` 的动画 `drawRect`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28876521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com