let searchBar = UISearchBar()
searchBar.placeholder = ChatConstants.searchTitle
searchBar.backgroundColor = .white
searchBar.delegate = self
searchBar.vCornerRadius = 20
searchBar.vBorderWidth = 1
searchBar.vBorderColor = .icedGray
searchBar.searchBarStyle = .minimal
searchBar.searchTextField.backgroundColor = .white
searchBar.translatesAutoresizingMaskIntoConstraints = false
if let textField = searchBar.value(forKey: ExploreConstants.searchFieldKey) as? UITextField {
let whiteColor = UIColor.white
let attributedString = NSAttributedString(string: "Search", attributes: [NSAttributedString.Key.foregroundColor: whiteColor])
textField.attributedPlaceholder = attributedString
textField.font = UIFont.regularDMSans(of: ExploreConstants.textFieldFontSize)
textField.layer.cornerRadius = ExploreConstants.searchBarCornerRadius
if let searchIcon = UIImage(named: ExploreConstants.iconExploreSearch) {
let imageView = UIImageView(image: searchIcon)
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: ExploreConstants.searchIconOffset + searchIcon.size.width, height: searchIcon.size.height))
imageView.frame = CGRect(x: ExploreConstants.searchIconOffset, y: 0, width: searchIcon.size.width, height: searchIcon.size.height)
paddingView.addSubview(imageView)
textField.leftView = paddingView
textField.leftViewMode = .always
}
}
我正在配置搜索栏,如上所示。但是,我无法将图像中看到的灰色区域变成白色。我怎样才能把这个区域变成白色?
我预计通过将 UIView 的背景颜色更改为白色,搜索栏中的灰色区域也会变成白色。
if let backgroundView = searchBar.subviews.first?.subviews.first(where: { $0 is UIImageView }) as? UIImageView {
backgroundView.backgroundColor = .white
backgroundView.alpha = 0 // Or set isHidden to true if you want to remove the background entirely
}