如何在swift,iOS中制作自定义进度条?

我想根据百分比(10%,30%50%……)将黑色填充到UIView在此处输入图像描述

这样做的正确方法是什么?

如果它是您要查找的自定义进度条,请尝试以下操作: –

 class ViewController: UIViewController { @IBOutlet weak var viewProg: UIView! // your parent view, Just a blank view let viewCornerRadius : CGFloat = 5 var borderLayer : CAShapeLayer = CAShapeLayer() let progressLayer : CAShapeLayer = CAShapeLayer() override func viewDidLoad() { super.viewDidLoad() viewProg.layer.cornerRadius = viewCornerRadius drawProgressLayer() } func drawProgressLayer(){ let bezierPath = UIBezierPath(roundedRect: viewProg.bounds, cornerRadius: viewCornerRadius) bezierPath.closePath() borderLayer.path = bezierPath.CGPath borderLayer.fillColor = UIColor.blackColor().CGColor borderLayer.strokeEnd = 0 viewProg.layer.addSublayer(borderLayer) } //Make sure the value that you want in the function `rectProgress` that is going to define //the width of your progress bar must be in the range of // 0 <--> viewProg.bounds.width - 10 , reason why to keep the layer inside the view with some border left spare. //if you are receiving your progress values in 0.00 -- 1.00 range , just multiply your progress values to viewProg.bounds.width - 10 and send them as *incremented:* parameter in this func func rectProgress(incremented : CGFloat){ print(incremented) if incremented <= viewProg.bounds.width - 10{ progressLayer.removeFromSuperlayer() let bezierPathProg = UIBezierPath(roundedRect: CGRectMake(5, 5, incremented , viewProg.bounds.height - 10) , cornerRadius: viewCornerRadius) bezierPathProg.closePath() progressLayer.path = bezierPathProg.CGPath progressLayer.fillColor = UIColor.whiteColor().CGColor borderLayer.addSublayer(progressLayer) } } } 

PS: - 您要做的事情也可以通过一条特定点定义的线作为起点和终点来实现,相应地设置线条宽度然后设置它的strokeEnd动画但是找到点是一个巨大的痛苦(因为你需要知道屏幕的帧大小,然后导航到视图等等......我不是说你不能)所以我更喜欢这个,

这样做的方法很少。

  1. 创建UIView的子类,并在drawRect方法中绘制您需要的确切区域。
  2. 在视图中添加新的UIView对象(图像上为白色)(黑色)。