class CustomSearchBar: UISearchBar {
private let toLabel: UILabel = {
let label = UILabel()
label.text = "To:"
label.textColor = .label
label.font = UIFont.systemFont(ofSize: 17, weight: .medium)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
configureUI()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configureUI()
}
private func configureUI() {
self.searchTextField.backgroundColor = .clear
self.searchTextField.clearButtonMode = .never
self.backgroundImage = UIImage()
self.setImage(UIImage(), for: .search, state: .normal)
self.searchTextField.tokenBackgroundColor = UIColor.secondaryBackgroundColor
self.tintColor = .label
// Add "To:" label to the search bar
self.addSubview(toLabel)
toLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 12).isActive = true
toLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
// Set up the text field to start after the "To:" label
self.searchTextField.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.searchTextField)
self.searchTextField.leadingAnchor.constraint(equalTo: toLabel.trailingAnchor, constant: 8).isActive = true
self.searchTextField.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -12).isActive = true
self.searchTextField.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
override func layoutSubviews() {
super.layoutSubviews()
// Adjust text field frame to prevent overlap with the "To:" label
let textField = self.searchTextField
let xValue = toLabel.frame.maxX + 8
let width = self.frame.width - 12 - xValue - 12
textField.frame = CGRect(x: xValue, y: textField.frame.minY, width: width, height: textField.frame.height)
}
}
I created a custom search bar as above. The search bar text starts after To: Label. I added it as an outlet in ViewController. It works fine when the view is loaded, but when I move the app from background to foreground search bar text overlaps with To: Label.
I tried calling viewWillLayoutSubview, searchBar.layoutSubviews(), searchBar.layoutIfNeeded() in the viewWillAppear method. It didn't work. Can you suggest how to fix this?