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

时间:2016-08-29 20:55:19

标签: ios iphone swift uiview

我想根据百分比(10%,30%50%......)将黑色填充到UIViewenter image description here

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

2 个答案:

答案 0 :(得分:5)

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

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: - 您要尝试做的也可以通过使用某个特定点定义的线作为起点和终点来实现,相应地设置线lineWidth然后设置其 strokeEnd 但找到分数是一个巨大的痛苦(因为你需要知道屏幕的框架大小然后导航到视图等等......我不是说你不能)所以我更喜欢这个,< / p>

答案 1 :(得分:3)

实现目标的方法很少。

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