删除UISearchBar左侧的图像可以通过以下方法实现:
func getSubviews(view: UIView) -> [UIView] {
var subviews = [UIView]()
for subview in view.subviews {
subviews.append(subview)
subviews.append(contentsOf: getSubviews(view: subview))
}
return subviews
}
let searchBar = UISearchBar()
let subviews = getSubviews(view: searchBar)
for subview in subviews {
if let imageView = subview as? UIImageView, let image = imageView.image {
if image.size.width == searchBar.height && image.size.height == searchBar.height {
imageView.removeFromSuperview()
break
}
}
}
searchFieldLeftPadding
属性,以删除左侧的图像空间。extension UISearchBar {
var searchField: UITextField? {
return value(forKey: "searchField") as? UITextField
}
var searchFieldLeftView: UIView? {
return searchField?.leftView
}
var searchFieldLeftPadding: CGFloat {
get {
return searchFieldLeftView?.frame.width ?? 0
}
set {
let leftView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: searchField?.frame.height ?? 0))
searchField?.leftView = leftView
searchField?.leftViewMode = .always
}
}
}
searchBar.searchFieldLeftPadding = 0
通过以上方法,可以删除UISearchBar左侧的图像,并且保留搜索框文本字段的功能。
领取专属 10元无门槛券
手把手带您无忧上云