如何在iOS的Swift中制作自定义进度栏? [英] How to make a custom progress bar in swift, iOS?

查看:67
本文介绍了如何在iOS的Swift中制作自定义进度栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要根据百分比(10%,30%50%...)将黑色填充为UIView?

I want to fill black color to UIView, based on percentage (10%, 30% 50%...)?

执行此操作的正确方法是什么?

What is the right way to do this?

推荐答案

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

If it is a custom progress bar you are looking for , Try this :-

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 设置动画,但是找到这些点是一个巨大的痛苦(因为您需要知道屏幕的帧大小才能导航到视图,依此类推……我不是说您不能),所以我更愿意这样做,

PS:- What you are trying to do can also be achieved by a line defined with some particular point as start and end points , set the lines lineWidth accordingly and then animates its strokeEnd but finding the points is a huge pain(because you need to know the frame size of the screen to then navigate to the view and so on... i'm not saying you cant) so i would prefer this,

这篇关于如何在iOS的Swift中制作自定义进度栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆