我正在嘗試創建一個簡單的水平進度欄視圖,並且想要動畫我的寬度約束。爲自定義進度條設置動畫寬度約束Autolayout
出於測試目的,我創建了一個按鈕,可以在點擊時增加進度條的百分比。
當我點擊按鈕時,寬度約束按預期動畫。但是,如果我在初始化組件時嘗試設置一個百分比,整個視圖就會生成動畫,這不是我想要的。
class ProgressBar: UIView {
private let progressView: UIView
private var progressBarWidth: NSLayoutConstraint? = nil
var percentage: Double = 0 {
didSet {
updateProgress()
}
}
init() {
progressView = UIView()
super.init(frame: .zero)
setupBackgroundBar()
setupProgressView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupBackgroundBar() {
self.heightAnchor.constraint(equalToConstant: 10).isActive = true
self.backgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.5)
}
private func setupProgressView(){
self.addSubview(progressView)
progressView.translatesAutoresizingMaskIntoConstraints = false
progressView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
progressView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
progressView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
progressView.backgroundColor = UIColor.white
}
func updateProgress() {
let progressMultiplier = CGFloat(percentage/100)
UIView.animate(withDuration: 1.0) {
if let progressConstraint = self.progressBarWidth {
NSLayoutConstraint.deactivate([progressConstraint])
}
self.progressBarWidth = self.progressView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: progressMultiplier)
self.progressBarWidth?.isActive = true
self.layoutIfNeeded()
}
}
}
視圖控制器
class ViewController: UIViewController {
let progressBar: ProgressBar
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
self.view.addSubview(progressBar)
progressBar.translatesAutoresizingMaskIntoConstraints = false
progressBar.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 30).isActive = true
progressBar.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 30).isActive = true
progressBar.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -30).isActive = true
let button = UIButton(type: .roundedRect)
self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = UIColor.white
button.setTitleColor(UIColor.black, for: .normal)
button.setTitle("Increase 1%", for: .normal)
button.topAnchor.constraint(equalTo: progressBar.bottomAnchor, constant: 10).isActive = true
button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
button.addTarget(self, action:#selector(self.buttonTapped), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
progressBar = ProgressBar()
super.init(coder: aDecoder)
}
func buttonTapped() {
progressBar.percentage += 1
}
}
我想我初始化視圖,就像當我點擊按鈕正好儘快動畫寬度約束。
您是否嘗試過使用CAShapeLayer和strokeBegin strokeEnd propertys?我認爲這是最好的方法 –