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

AAV*_*AAV -2 iphone uiview ios swift

我希望UIView根据百分比(10%,30%50%......)填充黑色? 在此输入图像描述

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

Dra*_*ian 6

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

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)

    }

  }
}
Run Code Online (Sandbox Code Playgroud)

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