iosiphoneswift3xcode8

How to make waved progress bar in swift?


I am beginner IOS developer and often see in design patterns that people use Heart Beat or Waves as the progression bar (i.e. song progress). Sometimes these progress bars go around theAlbum Art etc.

How can i achieve such thing? I am aware of UISlider combined with AVAudioPlayer but couldn't find anything to achieve such as following for song slider.

enter image description here


Solution

  • You could make a custom View, and draw the vertical lines manually. The main procedure for reference:

    import UIKit
    
    class WavedProgressView: UIView {
    
        var lineMargin:CGFloat = 2.0
        var volumes:[CGFloat] = [0.5,0.3,0.2,0.6,0.4,0.5,0.8,0.6,0.4]
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.backgroundColor = UIColor.darkGray
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            self.backgroundColor = UIColor.darkGray
        }
    
        override var frame: CGRect {
            didSet{
                self.drawVerticalLines()
            }
        }
    
        var lineWidth:CGFloat = 3.0{
            didSet{
                self.drawVerticalLines()
            }
        }
    
        func drawVerticalLines() {
            let linePath = CGMutablePath()
            for i in 0..<self.volumes.count {
                let height = self.frame.height * volumes[i]
                let y = (self.frame.height - height) / 2.0
                linePath.addRect(CGRect(x: lineMargin + (lineMargin + lineWidth) * CGFloat(i), y: y, width: lineWidth, height: height))
            }
    
            let lineLayer = CAShapeLayer()
            lineLayer.path = linePath
            lineLayer.lineWidth = 0.5
            lineLayer.strokeColor = UIColor.white.cgColor
            lineLayer.fillColor = UIColor.white.cgColor
            self.layer.sublayers?.removeAll()
            self.layer.addSublayer(lineLayer)
        }
    }
    

    The effect is:
    enter image description here

    And please make it more perfect by yourself, like: handling event, applying default and highlighted color etc.