我的UITableView中有多个部分,我想更改我的视图 背景色为渐变色,平滑过渡时 滚动tableView。
当新的部分进入tableView更改视图背景颜色时 顺利进行。
我如何实现这种动画。
我的代码如下所示,用于更改背景颜色但不顺畅
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
switch section {
case 0:
self.view.backgroundColor = UIColor.cyan
break
case 1:
self.view.backgroundColor = UIColor.red
break
case 2:
self.view.backgroundColor = UIColor.green
break
case 3:
self.view.backgroundColor = UIColor.blue
break
case 4:
self.view.backgroundColor = UIColor.brown
break
default:
self.view.backgroundColor = UIColor.brown
break
}
}
答案 0 :(得分:0)
您可以尝试使用此代码。
func tableView(_ tableView: UITableView, willDisplayHeaderView view:
UIView, forSection section: Int) {
switch section {
case 0:
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseIn, .curveEaseOut, .allowUserInteraction], animations: {() -> Void in
self.view.backgroundColor = UIColor.cyan.withAlphaComponent(0.4)
})
case 1:
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseIn, .curveEaseOut, .allowUserInteraction], animations: {() -> Void in
self.view.backgroundColor = UIColor.green.withAlphaComponent(0.4)
})
case 2:
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseIn, .curveEaseOut, .allowUserInteraction], animations: {() -> Void in
self.view.backgroundColor = UIColor.yellow.withAlphaComponent(0.4)
})
case 3:
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseIn, .curveEaseOut, .allowUserInteraction], animations: {() -> Void in
self.view.backgroundColor = UIColor.orange.withAlphaComponent(0.4)
})
case 4:
UIView.animate(withDuration: 0.5, delay: 0.0, options: [.curveEaseIn, .curveEaseOut, .allowUserInteraction], animations: {() -> Void in
self.view.backgroundColor = UIColor.magenta.withAlphaComponent(0.4)
})
default:
self.view.backgroundColor = UIColor.brown
}
}
答案 1 :(得分:0)
您可以使用此代码平滑地更改视图渐变颜色 -
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
for layer in self.view.layer.sublayers! {
if layer .isKind(of: CAGradientLayer.self) {
layer.removeFromSuperlayer()
}
}
let gradient = CAGradientLayer()
gradient.frame = self.view.bounds
gradient.colors = [self.generateRandomColor().cgColor, self.generateRandomColor().cgColor]
let anim:CABasicAnimation = CABasicAnimation.init(keyPath: "opacity")
anim.fromValue = 0.5
anim.toValue = 1
anim.duration = 1.0
gradient.add(anim, forKey: "opacity")
self.view.layer.addSublayer(gradient)
self.view.layoutIfNeeded()
}
func generateRandomColor() -> UIColor {
let hue : CGFloat = CGFloat(arc4random() % 256) / 256 + 0.5
let saturation : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5
let brightness : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 0.5)
}