Search code examples
swiftrating

Percent Rating Bar in Swift


I have data on votes/total votes and I would like to add a percent rating bar that shows the percentage of votes. ie: 95% and fills the bar 95%. I couldn't find any swift instruction on this (except to give UISlider a try).

Example:

Rating Bar (350/700 votes):
[==========50%            ]

Rating Bar (180/200 votes):
[==========90%==========  ]

Rating Bar (213/709 votes):
[======    30%            ]

Solution

  • Use a UIView as background view. Then, add another view as subview as the progress bar. Let`s implement that as a class:

    class ProgressView: UIView {
    
        var progress: CGFloat = 0
        var filledView: UIView
    
        override init(frame: CGRect) {
            filledView = UIView(frame: CGRect(x: frame.origin.x, y: frame.origin.y, width: 0, height: frame.height))
            filledView.backgroundColor = Colors.fontColor
    
            super.init(frame: frame)
            addSubview(filledView)
        }
    
        required init(coder aDecoder: NSCoder) { // <-- You need to implement this
            fatalError()
        }
    
        func setProgess(var progress: CGFloat) {
            progress = min(max(progress, 0), 1) // Between 0 and 1
            self.progress = progress
    
            filledView.frame.size.width = self.frame.width * progress
        }
    }
    

    Now you can also add a UILabel to show the percentage if you want to.