将 UIProgressView 添加到 UISearchBar,就像在 Safari 中一样



当您按下刷新时,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)
)
}

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

有人有更好的方法吗?

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.当您单击搜索栏时,您可以显示取消按钮并隐藏您的进度视图。我希望它能帮助你。

感谢virani-vevek为我指出正确的方向。这是一个可行的解决方案。

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
}

最新更新