Fill UIView with color based on percentage

2019-06-07 07:55发布

I have a UIView inside the UIView of UIViewController with Height = 149.0 and Width = 123.5.

I am filling this UIView with color, and I am setting the height of the color to be filled based on a response in percentage from a rest url.

How do I fill the entire View with the above mentioned dimensions for 100% and different values.

Any help will be appreciated. Thank you

标签: ios swift uiview
1条回答
放我归山
2楼-- · 2019-06-07 08:11

If you want to fill multiple color in your uiview then you need to subclass UIView and should override it's drawRect method something like,

 override func drawRect(rect: CGRect) {


    var percentage = CGFloat()  //can declare as instance variable or globally which you get from web service and set it's value!!



    percentage = 0.5

    let upperRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height*percentage)

    let lowerRect = CGRectMake(rect.origin.x, rect.origin.y + (rect.size.height * percentage), rect.size.width, rect.size.height * (1-percentage))

    UIColor.redColor().set()
    UIRectFill(upperRect)
    UIColor.greenColor().set()
    UIRectFill(lowerRect)



}
查看更多
登录 后发表回答