Search code examples
iosswiftuisearchbaruiprogressview

Adding a UIProgressView to UISearchBar like in Safari


When you press refresh, Safari's search bar displays a progress view.

My requirements are:

  1. the progress view should have rounded corners matching the search bar's corners

  2. the progress view width should adjust itself if a cancel button is shown.

Here is my naive attempt using PureLayout for constraints:

 if let tf = sb.textField {
      tf.addSubview(progressView)

      // Match the search bar's text field height - 1
      progressView.autoPinEdgesToSuperviewEdges(
        with: UIEdgeInsets(top: 0.0, left: 0.0, bottom: 1.0, right: 0.0)
      )
      progressView.isUserInteractionEnabled = false
      progressView.clipsToBounds = true
      progressView.layer.cornerRadius = 12

      let mask = UIView(forAutoLayout: ())
      mask.backgroundColor = UIColor(white: 0.0, alpha: 1.0)

      progressView.addSubview(mask)

      mask.autoPinEdgesToSuperviewEdges(
        with: UIEdgeInsets(top: 0.0, left: 0.0, bottom: 1.0, right: 0.0)
      )
    }

It works but the search bar's textfield loses its gray background.

Anyone's got a better approach?


Solution

  • Thanks to virani-vevek for pointing me in the right direction. Here is a working solution.

      if let tf = sb.textField {
          let back = UIView()
          tf.addSubview(back)
    
          back.autoPinEdgesToSuperviewEdges(
            with: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
          )
          back.backgroundColor = UIColor.clear
          back.isUserInteractionEnabled = false
          back.layer.cornerRadius = 12
          back.layer.masksToBounds = true
          back.addSubview(progress)
    
          progress.autoPinEdgesToSuperviewEdges(
            with: UIEdgeInsets(top: tf.frame.height - 1, left: 0, bottom: 0, right: 0)
          )
    
          progress.trackTintColor = .clear
          progress.tintColor = Theme.current.tintColor
          progress.progress = 0.5 // debug value
        }