我有一个将多个图像上传到Firebase的项目,并制作了一个常数来计算当前上传进度的百分比:
uploadTask.observe(.progress, handler: { (snapshot) in
guard let progress = snapshot.progress else {
return
}
let percentage = (Float(progress.completedUnitCount) / Float(progress.totalUnitCount))
progressBlock(Double(percentage))
})
我制作了一个UIView元素,但尚未连接它。我正在尝试使UIView充当进度条,以便用户可见地查看上传进度。我一直在尝试这样做,但是没有成功。我怎样才能做到这一点?顺便说一句:UIView应该随着percentage
的增加而增加,并且100%时,UIView将重置并隐藏。
非常感谢您!
答案 0 :(得分:2)
创建UIView
的自定义子类。为自定义子类赋予属性percentComplete
。
让视图使用CAShapeLayer
绘制一个填充区域,该区域会随着百分比值从0.0增加到1.0而扩展以填充视图。 (您也可以覆盖drawRect()
方法并使用Quartz绘图,但是形状图层更容易且性能更高。
在CAShapeLayer
上进行一些搜索,以获取有关操作方法的想法。
您可以让视图在视图上添加形状层作为附加层,也可以让视图提供layerClass
属性,使视图的内容层成为单个CAShapeLayer
答案 1 :(得分:0)
这是用于动态更改视图宽度的代码。
import UIKit
class ViewController: UIViewController {
var widthAnchor:NSLayoutConstraint!
let perecentageView:UIView={
let view = UIView()
view.backgroundColor = .red
view.translatesAutoresizingMaskIntoConstraints = false//Its needed becasue we are using anchors
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(perecentageView)
perecentageView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 100).isActive = true
perecentageView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 10).isActive = true
perecentageView.heightAnchor.constraint(equalToConstant: 50).isActive = true
widthAnchor = perecentageView.widthAnchor.constraint(equalToConstant: 0) // By default its 0
widthAnchor.isActive = true
self.uploadProgess()
}
func uploadProgess(){
uploadTask.observe(.progress, handler: { (snapshot) in
guard let progress = snapshot.progress else {
return
}
let percentage = (Float(progress.completedUnitCount) / Float(progress.totalUnitCount))
let newWidth = self.view.frame.width * percentage / 100
DispatchQueue.main.async(execute: {
self.widthAnchor.constant = newWidth
// self.view.frame.width is the parent view (And max width will be = self.view.frame.width)
//if you are using view from storybard with aoutolayout then just take IBOutlet of view's with and here widthAnchor = your IBOutlet
/*
if you are using view from storybard and without autolayout then use below code
self.perecentageView.frame = CGRect(x: self.perecentageView.frame.origin.x, y: self.perecentageView.frame.origin.y, width: newWidth, height: self.perecentageView.frame.height)
*/
})
})
}
}