【问题标题】:Fill in Horizontal View with Animation (Swift)用动画填充水平视图(Swift)
【发布时间】:2018-08-07 03:51:52
【问题描述】:

我正在尝试用动画填充水平视图(如进度条之类)(因此它将从左边缘填充到右侧)。

这是我拥有的,但它不起作用

override init(frame: CGRect) {
    super.init(frame: frame)

    let outlineView = UIView()
    outlineView.layer.borderColor = UIColor.black.cgColor
    outlineView.layer.borderWidth = 1
    endorsementViews.append(outlineView)

    addSubview(outlineView)

    // custom UIView anchor extension
    outlineView.anchor(topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 12, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 75)

    let fillView = UIView()
    fillView.backgroundColor = .orange
    fillView.alpha = 0
    fillViews.append(fillView)

    outlineView.addSubview(fillView)

    // custom UIView anchor extension     
    fillView.anchor(outlineView.topAnchor, left: outlineView.leftAnchor, bottom: outlineView.bottomAnchor, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 195, heightConstant: 0)
}

override func layoutSubviews() {
    super.layoutSubviews()

    for index in 0...2 {
        let fillWidth = 75

        UIView.animate(withDuration: 3.5) {
            self.fillViews[index].frame.size.width = fillWidth
        }
    }
}

【问题讨论】:

标签: swift animation uiview uiviewanimation


【解决方案1】:

您不需要在layoutSubviews() 方法中更改动画。如果您在动画中更改视图的大小,您的fillView 的大小也会在动画中发生变化。

但是,如果您想根据情况更改fillView 的框架:您应该在动作(或函数)中执行此操作,并在动画函数底部使用视图的layoutIfNeeded() 方法,如下所示:

func someFunction() {
    let fillWidth = 75
    UIView.animate(withDuration: 3.5)
       for index in 0...2 {
           self.fillViews[index].frame.size.width = fillWidth
       }
       self.layoutIfNeeded()
    }
}

注意: 您应该避免同时使用frame 属性和约束来将框架设置为相同的视图。您可以在动画中更改视图的约束属性或在layoutSubviews() 方法中设置视图的框架,并使用布尔控件检查子视图的实际状态以设置特定的框架(如果需要)。

【讨论】:

    猜你喜欢
    • 2011-07-15
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多