如何在swift中自动在搜索栏中显示光标



我在viewcontroller中有搜索栏。当我点击搜索栏时,光标会显示出来,但当我到达视图控制器时,我需要在搜索栏上显示光标。如何进行

代码:我已经尝试了以下代码。。当我点击搜索栏光标时,显示。。当我到达这个视图时,我需要光标自动显示在搜索栏上。。怎样请引导

class PlaceViewController: UIViewController, UISearchControllerDelegate, UISearchBarDelegate {
var resultsViewController: GMSAutocompleteResultsViewController?
var searchController: UISearchController?
var delegate: PlaceViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()

view.backgroundColor = .secondarySystemBackground
title = "Select Address".localizedWithLanguage

searchController = UISearchController(searchResultsController: resultsViewController)
searchController?.searchResultsUpdater = resultsViewController
searchController?.searchBar.placeholder = "please start typing here"
searchController?.searchBar.tintColor = view.tintColor
searchController?.searchBar.showsCancelButton = true
searchController?.delegate = self
searchController?.searchBar.delegate = self
searchController?.searchBar.becomeFirstResponder()
let subView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 45.0))
subView.addSubview((searchController?.searchBar)!)
view.addSubview(subView)
definesPresentationContext = true
}
private func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
searchController?.searchBar.tintColor = UIColor.blue
return true
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.endEditing(true)
dismiss(animated: true)
}
}

请在这样的DispatchQueue异步函数中添加becomeFirstResponder行代码。它应该起作用。

DispatchQueue.main.async {
self.searchController?.searchBar.becomeFirstResponder()
}

您需要使用DispatchQueue异步方法使searchBar成为主线程上的第一个响应程序。

最新更新