Reputation: 1709
I've been searching all over on how to change the height of the text field inside of a UISearchBar. This is my current code, which does not do what I want. I'm wondering what I need to change to get the desired results.
Search bar initialization
private var searchBar: UISearchBar = {
let search = UISearchBar()
search.translatesAutoresizingMaskIntoConstraints = false
search.searchBarStyle = .default
search.barTintColor = .none
search.placeholder = "Search project"
return search
}()
Search bar constraints (called in viewDidLoad()
)
searchBar.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
searchBar.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
searchBar.heightAnchor.constraint(equalToConstant: 42).isActive = true
searchBar.widthAnchor.constraint(equalToConstant: 265).isActive = true
Search bar style (called in viewDidLayoutSubviews()
)
super.viewDidLayoutSubviews()
self.searchBar.layoutIfNeeded()
self.searchBar.layoutSubviews()
let searchTextField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField
var currentTextFieldBounds = searchTextField?.bounds
currentTextFieldBounds?.size.height = 130
searchTextField?.bounds = currentTextFieldBounds ?? CGRect.zero
searchBar.layoutIfNeeded()
searchBar.layoutSubviews()
Upvotes: 1
Views: 1895
Reputation: 161
I managed to increase the height of UISearchBar by adding a background image, to resize the entire search bar frame, and then managed to resize textField by changing the font size.
First change the search bar height constraint:
searchBar.heightAnchor.constraint(equalToConstant: 130).isActive = true
Create the function that will programatically create a background image for the search bar:
func getImageWithCustomColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
Then change font size on viewDidLayoutSubviews:
override func viewDidLayoutSubviews() {
self.searchBar.layoutIfNeeded()
self.searchBar.layoutSubviews()
self.searchBar.searchTextField.font = .systemFont(ofSize: 60.0)
//Your custom text size
searchBar.layoutIfNeeded()
searchBar.layoutSubviews()
}
Finally, in viewDidLoad create an image of the same size as the desired textField custom size (your case, 130) and call the function to place the background image of the desired color on the search Bar (this case, a clear background):
let backgroundImage = getImageWithCustomColor(color: UIColor.clear, size: CGSize(width: 265, height: 130))
searchBar.setSearchFieldBackgroundImage(backgroundImage, for: .normal)
This is the output
Hope this helps.
Upvotes: 3