删除UISearchBar文本字段周围的填充

时间:2019-04-11 15:46:33

标签: ios swift autolayout uitextfield uisearchbar

我正在尝试在UISearchBar中使文本字段左对齐。

我在下面谈论紫色区域。

enter image description here

我已经可以通过将背景设置为.clear来隐藏它,但是现在我希望文本字段与上方文本的前边缘对齐。我不确定应该调整哪个属性以正确地使整个搜索字段左对齐。

enter image description here

2 个答案:

答案 0 :(得分:1)

不幸的是,无法可靠地删除此填充。当前(自iOS 13开始)水平填充为8点,垂直填充为10点。

您只需在“ Discogs | Search”视图中设置前导/尾随约束+ 8点即可使其大小相同。

我需要做一些类似于在SwiftUI中包装UISearchBar的事情,但是在padding UISearchBar上使用UIViewRepresentable修饰符是这样的:

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
    }
}

答案 1 :(得分:0)

可以通过将backgroundimage更改为nil来帮助: searchBar.backgroundImage = nil