I am trying to left align the text field within a UISearchBar
.
I am talking about the area in purple below.
I have been able to hide this by setting the background as .clear
however I would now like the text field to align with the leading edge of the text above. I am unsure what property I should adjust to properly left align the entire search field.
Unfortunately there is no way to reliably remove this padding. Currently (as of iOS 13) the horizontal padding is 8 pts, and the vertical is 10 pts.
You can simply set the leading/trailing constraints to the "Discogs|Search" view + 8 pts to make it appear the same size.
I needed to do something similar to wrap UISearchBar
in SwiftUI, but instead used the padding
modifier on the UISearchBar
UIViewRepresentable
like so:
struct SearchBar: View {
private var title: String = "Search"
@Binding private var text: String
private var onEditingChanged: (Bool) -> Void
init(
_ title: String,
text: Binding<String>,
onEditingChanged: @escaping (Bool) -> Void = { _ in }
) {
self.title = title
self._text = text
self.onEditingChanged = onEditingChanged
}
var body: some View {
__SearchBar(title, text: $text, onEditingChanged: onEditingChanged)
.padding(.horizontal, -8)
.padding(.vertical, -10)
}
}
private struct __SearchBar: UIViewRepresentable {
private var placeHolder: String = "Search"
@Binding private var text: String
private var onEditingChanged: (Bool) -> Void
init(
_ title: String,
text: Binding<String>,
onEditingChanged: @escaping (Bool) -> Void
) {
self.placeHolder = title
self._text = text
self.onEditingChanged = onEditingChanged
}
final class Coordinator: NSObject, UISearchBarDelegate {
private let parent: __SearchBar
@Binding var text: String
init(parent: __SearchBar, text: Binding<String>) {
self.parent = parent
_text = text
}
func searchBar(
_ searchBar: UISearchBar,
textDidChange searchText: String
) {
text = searchText
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
parent.onEditingChanged(true)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
parent.onEditingChanged(false)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self, text: $text)
}
func makeUIView(context: Context) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.placeholder = placeHolder
searchBar.searchBarStyle = .minimal
searchBar.delegate = context.coordinator
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: Context) {
uiView.text = text
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With