无法更改搜索栏的颜色,选择时它会跳到视图顶部



我正在尝试将搜索栏附加到我的表格视图顶部并更改其属性(例如颜色、占位符(。但是,我不知道如何。我尝试将tableView嵌入另一个视图中,但这没有帮助。有什么想法吗?

func setupSearch(){
search.delegate = self
search.automaticallyShowsCancelButton = false
search.searchBar.tintColor = UIColor.red
search.searchBar.barTintColor = UIColor.red
search.obscuresBackgroundDuringPresentation = false
search.hidesNavigationBarDuringPresentation = false
search.searchBar.placeholder = "Type something here to search"
navigationItem.searchController = search
tableView.tableHeaderView = search.searchBar
}

此函数在 viewDidLoad(( 中调用,并且添加了 tableView,但不使用正确的颜色或占位符,并在选择时跳转到屏幕顶部。 任何帮助将不胜感激。

这是setupSearch的更新代码(除了选择时栏跳到顶部之外,一切正常(:

func setupSearch(){
search.delegate = self
search.automaticallyShowsCancelButton = false
search.searchBar.barTintColor = UIColor.red
search.obscuresBackgroundDuringPresentation = false
search.hidesNavigationBarDuringPresentation = false
tableView.tableHeaderView = search.searchBar
}

我在开始时使用以下方法声明搜索栏:

let search = UISearchController(searchResultsController: nil)

关于如何阻止酒吧跳到顶部的任何想法?

只需将搜索栏添加为表视图的标题视图,而不是使用导航的项目搜索控制器(不要像在代码中那样添加具有两者(表视图和导航(的搜索栏(。您可以尝试使用下面的更新代码:

func setupSearch(){
search.delegate = self
search.automaticallyShowsCancelButton = false
search.searchBar.barTintColor = UIColor.red
search.obscuresBackgroundDuringPresentation = false
search.hidesNavigationBarDuringPresentation = false
search.searchBar.placeholder = "Type something here to search"
tableView.tableHeaderView = search.searchBar
self.definesPresentationContext = true
}
override func viewDidLoad() {
super.viewDidLoad()
setupSearch()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) // be notified when the keyboard changes your table View frame
}

@objc func keyboardWillShow(notification: NSNotification) {
tableView.frame.origin.y = 0 // reset the table view to its original coordinates 
}

func setupSearch(){
// for iOS 12 and lower, you can change the placeholder like this :
let textFieldSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldSearchBar?.textColor = .red
let searchBarLabel = textFieldSearchBar!.value(forKey: "placeholderLabel") as? UILabel
textFieldSearchBarLabel?.textColor = .red
}

相关内容

  • 没有找到相关文章

最新更新