首页 > 解决方案 > 如何创建垂直进度条 - IOS - Swift

问题描述

我正在尝试创建一个垂直进度条。但问题是我的代码在IOS11 或更高版本上运行,但在IOS9上却无法运行。

IOS11 或更高版本上看起来像: 在此处输入图像描述

但在IOS9上看起来像:在此处输入图像描述

我的代码:

let progressBar: UIProgressView = {
    let prgressView = UIProgressView()
    prgressView.progress = 0.7
    prgressView.progressTintColor = UIColor(red: 1.0, green: 0.21, blue: 0.33, alpha: 1)
    prgressView.trackTintColor = UIColor.blue
    prgressView.layer.cornerRadius = 6.5
    prgressView.clipsToBounds = true
    prgressView.transform = CGAffineTransform(rotationAngle: .pi / -2)
    prgressView.translatesAutoresizingMaskIntoConstraints = false
    return prgressView
}()

布局子视图()

override func layoutSubviews() {
    super.layoutSubviews()

    let width = progressBar.bounds.width
    let height = progressBar.bounds.height

    progressBar.bounds.size.width = height
    progressBar.bounds.size.height = width
}

viewDidLoad()

    self.addSubview(progressBar)
    progressBar.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    progressBar.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    progressBar.widthAnchor.constraint(equalToConstant: 22.5).isActive = true
    progressBar.heightAnchor.constraint(equalToConstant: 250).isActive = true

我正在按照本教程创建垂直进度视图:https ://www.youtube.com/watch?v=ifekgTtb0rQ&t=1070s

标签: iosswiftuiprogressview

解决方案


通过对您发布的代码进行两项更改,我能够使您的代码在 iOS 9 和 iOS 12 下正常工作:

  1. 删除layoutSubviews. 你已经设置了约束。也不要尝试直接修改视图的框架。
  2. Swap the width and height constraints. Think about the size of the progress bar if you didn't apply the transform. You want the width to be 250 and the height to be 22.5. The transform doesn't change this. The transform only makes it look like it's 250 tall but it is still 250 wide.

In short, remove layoutSubviews and fix your constraints to:

progressBar.widthAnchor.constraint(equalToConstant: 250).isActive = true
progressBar.heightAnchor.constraint(equalToConstant: 22.5).isActive = true

推荐阅读