[英]Remove padding around UISearchBar textfield
I am trying to left align the text field within a UISearchBar
.我试图在
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.我已经能够通过将背景设置为
.clear
来隐藏它,但是我现在希望文本字段与上面文本的前缘对齐。 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.
当前(从 iOS 13 开始)水平填充为 8 磅,垂直填充为 10 磅。
You can simply set the leading/trailing constraints to the "Discogs|Search" view + 8 pts to make it appear the same size.您可以简单地将前导/尾随约束设置为“Discogs|Search”视图 + 8 pts 以使其显示相同的大小。
I needed to do something similar to wrap UISearchBar
in SwiftUI, but instead used the padding
modifier on the UISearchBar
UIViewRepresentable
like so:我需要做一些类似于在 SwiftUI 中包装
UISearchBar
的事情,而是在UISearchBar
UIViewRepresentable
上使用padding
修饰符,如下所示:
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
}
}
通过将backgroundimage更改为nil可以有所帮助:searchBar.backgroundImage = nil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.