我们正在寻求实现类似“ butterbar”的功能,它基本上是一个UIView,其颜色从中间向外变化到边缘。例如codepen。
How to do this in swift?
答案 0 :(得分:3)
这是您的解决方案。基本上,有一个ButterBar
UIView
子类,它具有一个内部视图子视图和多种颜色。
ButterBar
的宽度代码...
class ButterBar: UIView {
private let innerView = UIView(frame: .zero)
private var colours: [UIColor] = [.black, .white]
private var colourIndex = 0
private var isAnimating = false
private lazy var widthConstraint: NSLayoutConstraint = {
return innerView.widthAnchor.constraint(equalToConstant: 0)
}()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func configure(colours: [UIColor]) {
guard colours.count > 1 else { return }
self.colours = colours
}
func startAnimating() {
colourIndex = 0
isAnimating = true
updateColours()
animate()
}
func stopAnimating() {
isAnimating = false
}
}
private extension ButterBar {
func configure() {
innerView.translatesAutoresizingMaskIntoConstraints = false
addSubview(innerView)
topAnchor.constraint(equalTo: innerView.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: innerView.bottomAnchor).isActive = true
centerXAnchor.constraint(equalTo: innerView.centerXAnchor).isActive = true
widthConstraint.isActive = true
}
func updateColours() {
backgroundColor = colours[colourIndex]
colourIndex = (colourIndex + 1) % colours.count
innerView.backgroundColor = colours[colourIndex]
}
func animate() {
widthConstraint.constant = 0
layoutIfNeeded()
widthConstraint.constant = bounds.width
UIView.animate(withDuration: 1, animations: {
self.layoutIfNeeded()
}) { _ in
if self.isAnimating {
self.updateColours()
self.animate()
}
}
}
}
然后……
@IBOutlet weak var butterBar: ButterBar!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
butterBar.configure(colours: [.red, .blue, .green, .yellow])
butterBar.startAnimating()
}
答案 1 :(得分:1)
您可以使用两个UIView,这些UIView限制在父对象的中心并且具有宽度限制。只需设置第一个视图的背景颜色,并设置其宽度约束(从0到父视图的宽度)即可制作动画。完成此操作后,您可以将另一个视图放到最前面并对其宽度进行动画处理(从0到父视图的宽度),然后从初始视图重新开始以保持循环进行。