在Swift的导航栏中获取search栏
所以我尝试了一切,试图让search栏进入Swift的导航栏。 但遗憾的是我还没有得到它的工作,只是…
对于那些不知道我在说什么的人,我正在尝试做这样的事情
注意导航栏中的search栏。 所以这就是我目前使用的
self.searchDisplayController?.displaysSearchBarInNavigationBar = true
我popup在我的viewDidLoad
,然后当我加载我提交的应用程序,只是一个空的导航栏…. :(任何想法?
尝试这个
var leftNavBarButton = UIBarButtonItem(customView:Yoursearchbar) self.navigationItem.leftBarButtonItem = leftNavBarButton
更新
你保留一个懒惰的UISearchBar属性
lazy var searchBar:UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 200, 20))
在viewDidLoad中
searchBar.placeholder = "Your placeholder" var leftNavBarButton = UIBarButtonItem(customView:searchBar) self.navigationItem.leftBarButtonItem = leftNavBarButton
如果你想使用故事板只需拖动您的search栏作为sockets,然后用您的socketssearch栏replace懒惰属性
// create the search bar programatically since you won't be // able to drag one onto the navigation bar searchBar = UISearchBar() searchBar.sizeToFit() // the UIViewController comes with a navigationItem property // this will automatically be initialized for you if when the // view controller is added to a navigation controller's stack // you just need to set the titleView to be the search bar navigationItem.titleView = searchBar
在你的视图控制器中:
lazy var searchBar = UISearchBar(frame: CGRectZero) override func viewDidLoad() { super.viewDidLoad() searchBar.placeholder = "Search" navigationItem.titleView = searchBar }
这样做,通过设置navigationItem.titleView,search栏自动居中iPhone和iPad设备。 注意:只能用v8.4和v9.0进行testing
SWIFT 3
lazy var searchBar = UISearchBar(frame: CGRect.zero)
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.endEditing(true) searchBar.text = nil print("## search btn clicked : \(searchBar.text ?? "")") }