2014-11-04 100 views
37

因此,我尝试了一切尝试将搜索栏导入Swift中的导航栏。但遗憾的是我没有得到它的工作,只是还没有...在Swift中的导航栏中获取搜索栏

对于那些你们谁不知道我在说什么,我试图做这样的事情

enter image description here

请注意导航栏中的搜索栏。因此,这里就是我目前使用

self.searchDisplayController?.displaysSearchBarInNavigationBar = true 

我突然出现在我的viewDidLoad,然后当我加载了我提出与应用,只是一个空的导航栏.... :(任何想法?

回答

49

试试这个

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 

如果你想用故事板 只需将您的搜索栏作为一个出口,然后用插座搜索栏

+0

我将如何确定'Yoursearchbar'? – user302975 2014-11-04 02:13:57

+0

查看更新中的代码 – Leo 2014-11-04 02:24:25

+0

迄今为止这么好。但是,我将如何添加占位符?任何方式通过故事板? – user302975 2014-11-04 02:30:33

10

更换懒财产在您的视图控制器:

lazy var searchBar = UISearchBar(frame: CGRectZero) 

override func viewDidLoad() { 
    super.viewDidLoad() 

    searchBar.placeholder = "Search" 

    navigationItem.titleView = searchBar 
} 

这样做,通过设置navigationItem.titleVie w,搜索栏会自动对齐iPhone和iPad设备。注意:只有V8.4和V9.0

测试SWIFT 3

lazy var searchBar = UISearchBar(frame: CGRect.zero) 
+0

当用户点击“取消”按钮时如何从navigationItem.titleView中删除它? – Satyam 2017-04-28 16:18:21

+0

相同的问题^ – 2017-07-02 20:01:57

+1

如果你正在谈论搜索栏取消按钮,那么请关闭我的头顶。实现UISearchBarDelegate函数searchBarCancelButtonClicked(:),在该函数中调用navigationItem.titleView = nil。这应该删除搜索栏,如果这是你的意思是“删除它”。对于普通的搜索栏功能,还要确保你实现了searchBarSearchButtonClicked(:)添加searchBar.resignFirstResponder(),当点击搜索按钮时(或者通过返回键按下)删除键盘 – iAmcR 2017-07-04 16:39:28

30
// 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 
+0

这是一个比任何其他解决方案更好的方法。 – Profstyle 2016-05-06 12:32:35

+0

@ antonio081014,兄弟你能帮我看看我的问题吗?https://stackoverflow.com/questions/46375778/add-navigation-bar-in-uicollectionview-in-swift-4-ios-11? – 2017-09-23 03:47:11

0
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 

    searchBar.endEditing(true) 
    searchBar.text = nil 
    print("## search btn clicked : \(searchBar.text ?? "")") 
} 
+1

感谢您使用此代码段,这可能会提供一些有限的即时帮助。通过展示*为什么*这是一个很好的解决方案,并且使它对未来的读者更有用,一个正确的解释[将大大提高](// meta.stackexchange.com/q/114762)其长期价值其他类似的问题。请[编辑]你的答案以添加一些解释,包括你所做的假设。 – 2017-11-08 15:14:12