从下到上填充UIView

时间:2019-06-06 13:11:51

标签: ios swift

我有这个UIView,现在已经填充了静态浅灰色,我需要根据我从API提供的数字填充它。我尝试了几种方法,但对我不起作用。最简单的方法是什么?不必具有任何奇特的效果,只需一个简单的动画即可通过为其赋予数字来逐渐填充圆圈。

API返回的Int分别为0、10、20、30、40、50、60、70、80、90和100。 因此,鉴于这些数字,我必须使用它们来填充圆圈。它们基本上是百分比。因此10应该使圆圈填充10%。

这是我现在拥有的代码,它与ViewController位于同一文件中,但是我认为这不是最好的方法,或者至少它不起作用,因为当我尝试更新{ {1}}不会这样做。

coeff

它不起作用的确切原因是在这里:

class BadgeView: UIView {

    private let fillView = UIView(frame: CGRect.zero)
    private var fillHeightConstraint: NSLayoutConstraint!

    private(set) var coeff: CGFloat = 0.2 {
        didSet {
            updateFillViewFrame()
        }
    }

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

        setupView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setupView()
    }

    public func setupView() {
        layer.cornerRadius = bounds.height / 2.0
        layer.masksToBounds = true
        fillView.backgroundColor = UIColor(red: 220.0/255.0, green: 220.0/255.0, blue: 220.0/255.0, alpha: 0.4)
        fillView.translatesAutoresizingMaskIntoConstraints = false // ensure autolayout works
        addSubview(fillView)

        // pin view to leading, trailing and bottom to the container view
        fillView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        fillView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        fillView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true

        // save the constraint to be changed later
        fillHeightConstraint = fillView.heightAnchor.constraint(equalToConstant: 0)
        fillHeightConstraint.isActive = true
        updateFillViewFrame()
    }

    public func updateFillViewFrame() {
        fillHeightConstraint.constant = bounds.height * coeff // change the constraint value
        layoutIfNeeded() // update the layout when a constraint changes
    }

    public func setCoeff(coeff: CGFloat, animated: Bool) {
        if animated {
            UIView.animate(withDuration: 0.5, animations:{ () -> Void in
                self.coeff = coeff
            })
        } else {
            self.coeff = coeff
        }
    }
}

该行实际上并没有更新系数,因此它始终是先前设置的0.2。相反,它应该从0.0到1.0。

1 个答案:

答案 0 :(得分:0)

首先:我强烈建议使用框架以编程方式构建约束。像SnapKit之类的东西。

使用一个基本设置,其中有一个UIView(容器),其中包含另一个UIView(myView)。其中myView用于填充Container。 您可以使用以下代码(尽管没有完全测试)来设置约束的动画,并具有用container填充myView的效果

self.myView.snp_makeConstraints { make in
    make.left.right.bottom.equalTo(self.myContainer)
    make.height.equalTo(0)
}

let newPercentage = 10
UIView.animateWithDuration(0.3) {
    self.myView.snp_updateConstraints { make in
        make.height.equalTo(self.myContainer.frame.height / 100 * newPercentage)
    }
    self.myView.superview.layoutIfNeeded()
}
相关问题