【问题标题】:UIView fill animation in iOS Swift?iOS Swift中的UIView填充动画?
【发布时间】:2017-11-06 06:04:48
【问题描述】:

我想从左到右填充视图的颜色作为填充动画。我一直在使用此代码来获得效果,但不知何故它没有显示任何动画。我正在使用下面的代码。

UIView.animate(withDuration: 2.0, delay: 0.2, options:.curveLinear, animations: {
                view!.backgroundColor = Constant.AppColor.viewBottomFocus
            }, completion:nil)

请告诉我如何实现这一目标?

【问题讨论】:

  • 这个视图是您在故事板中创建的?或者你以编程方式抽屉?

标签: ios swift animation uiview


【解决方案1】:

我不认为你可以用简单的 UIView 块用从左到右的动画填充颜色。您当然可以更改视图的宽度或尾随约束,并且看起来视图正在更改其颜色。但是,我认为这不是理想的方式。

为了实现你想要的,我猜你必须使用渐变层并对位置进行动画处理:

class AnimatingV:UIView {

    func animate() {
        let layer = CAGradientLayer()
        let startLocations = [0, 0]
        let endLocations = [1, 2]

        layer.colors = [UIColor.red.cgColor, UIColor.white.cgColor]
        layer.frame = self.frame
        layer.locations = startLocations as [NSNumber]
        layer.startPoint = CGPoint(x: 0.0, y: 1.0)
        layer.endPoint = CGPoint(x: 1.0, y: 1.0)
        self.layer.addSublayer(layer)

        let anim = CABasicAnimation(keyPath: "locations")
        anim.fromValue = startLocations
        anim.toValue = endLocations
        anim.duration = 2.0
        layer.add(anim, forKey: "loc")
        layer.locations = endLocations as [NSNumber]
    }
}

let animatingV = AnimatingV(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
animatingV.backgroundColor = UIColor.yellow
animatingV.animate()
PlaygroundPage.current.liveView = animatingV

【讨论】:

  • 请告诉我一个更好的方法。我做不到?
  • @DhirajKumar:我不知道任何其他“更好”的方式。
【解决方案2】:

在 storyboard 中创建 UIView 并使其成为 UIProgressView 的子类 然后使用此代码填充视图,您也可以通过在调度程序中调用此函数来使用动画填充

//progressView is view that you have create in storyboard

progressView.progress = .25; // .25 is the fill rate of total view
progressView.trackTintColor = [UIColor whiteColor];
progressView.progressTintColor = [UIColor redColor];

【讨论】:

  • 虽然它正在填充颜色,但它不会动画
  • 在我的ans中提到的调度器中调用这个更改,并在那里传递增量百分比,然后你会看到动画填充
  • 我不能使用这种方法,因为我有一些 uiview 的初始颜色
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多