首页 > 解决方案 > 像在 Safari 中一样将 UIProgressView 添加到 UISearchBar

问题描述

当您按下刷新时,Safari 的搜索栏会显示一个进度视图。

我的要求是:

  1. 进度视图应该有与搜索栏角匹配的圆角

  2. 如果显示取消按钮,进度视图宽度应自行调整。

这是我使用 PureLayout 进行约束的天真的尝试:

 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)
      )
    }

它可以工作,但搜索栏的文本字段失去了灰色背景。

有人有更好的方法吗?

标签: iosswiftuisearchbaruiprogressview

解决方案


1. 你可以这样走,它完全适合我。代码如下:

let backview = UIView()
backview.backgroundColor = UIColor.clear
 DispatchQueue.main.async {
        let progress = UIProgressView()

        let searchfield = (self.searchbar.value(forKey: "searchField") as? UITextField)! //searchBar's textField

        progress.frame = CGRect(x: 0, y: searchfield.frame.height - 2, width: self.searchbar.subviews[0].subviews[1].frame.width  , height: 2)
        progress.tintColor = UIColor.systemBlue //Color you want
        progress.progress = 0.0
    
        backview.frame = searchfield.frame
        backview.autoresizingMask = .flexibleWidth
        backview.layer.cornerRadius = 10
        backview.layer.masksToBounds = true
        backview.isUserInteractionEnabled = false
        backview.addSubview(self.progress)

        self.searchbar.addSubview(backview) //self.searchbar is your UISearchBar
    }

2.当你点击searchBar你可以显示取消按钮和你的progressView隐藏。 我希望它会帮助你。


推荐阅读