如何在UISearchBar iOS 11中居中占位符文本

Sti*_*Sti 14 cocoa-touch uisearchbar ios ios11

在iOS 11中,searchBars默认为左对齐文本.虽然这对iOS的其他原生更改看起来很好,但它并不适合我的设计,我希望它像以前一样成为中心.

我找不到任何这样的对齐属性UISearchBar.我错过了什么,或者根本不可能?我是否必须创建自己的自定义搜索栏,例如从a派生UITextField来实现此目的?

小智 8

我有完全相同的问题 - 我很难理解为什么默认对齐将被更改而不允许我们轻松地将其设置回中心.

以下适合我(斯威夫特):

let placeholderWidth = 200 // Replace with whatever value works for your placeholder text
var offset = UIOffset()

override func viewDidLoad() {
    offset = UIOffset(horizontal: (searchBar.frame.width - placeholderWidth) / 2, vertical: 0)
    searchBar.setPositionAdjustment(offset, for: .search)
}

func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
    let noOffset = UIOffset(horizontal: 0, vertical: 0)
    searchBar.setPositionAdjustment(noOffset, for: .search)

    return true
}


func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
    searchBar.setPositionAdjustment(offset, for: .search)

    return true
}
Run Code Online (Sandbox Code Playgroud)


RJi*_*yes 3

这是一个解决方法。

首先,您需要获取搜索栏的文本字段并将文本对齐居中:

let textFieldOfSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField textFieldOfSearchBar?.textAlignment = .center

之后,您需要更改占位符的对齐方式。由于某种原因,它不会随着文本字段的对齐方式而改变。您应该仅在搜索控制器处于活动状态时向文本字段的左侧视图添加填充来实现此目的,因此请使用它的委托方法:

func presentSearchController(_ searchController: UISearchController) {
    //Is active
    let width: CGFloat = 100.0 //Calcualte a suitable width based on search bar width, screen size, etc..

    let textfieldOfSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField

    let paddingView = UIView(x: 0, y: 0, w: width, h: searchController.searchBar.frame.size.height)
    textfieldOfSearchBar?.leftView = paddingView
    textfieldOfSearchBar?.leftViewMode = .unlessEditing
}

func willDismissSearchController(_ searchController: UISearchController) {
    let textfieldOfSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField
    textfieldOfSearchBar?.leftView = nil
}
Run Code Online (Sandbox Code Playgroud)

祝你好运