本文介绍了如何设置动画在UINavigationBar的顶部添加UISearchBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在viewDidLoad
中设置了displaysSearchBarInNavigationBar = YES
,则视图显示时搜索栏将位于导航栏中.但是我想在触摸栏按钮项时在导航栏顶部显示搜索栏.就像下面的图片
If I set the displaysSearchBarInNavigationBar = YES
in viewDidLoad
, the search bar will be in navigation bar when the view show up. But I want to show search bar on top of navigation bar when I touch bar button item. It's like image below
常规导航栏:
搜索栏
推荐答案
我对Mark的答案做了一些修改,以使其能够在iOS 8中快速运行.
I've modified Mark's answer a little to get it to work in IOS 8 and in swift.
class ViewController : UIViewController, UISearchBarDelegate {
var searchBar = UISearchBar()
var searchBarButtonItem: UIBarButtonItem?
var logoImageView : UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Can replace logoImageView for titleLabel of navbar
let logoImage = UIImage(named: "logo-navbar")!
logoImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: logoImage.size.width, height: logoImage.size.height))
logoImageView.image = logoImage
navigationItem.titleView = logoImageView
searchBar.delegate = self
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBarButtonItem = navigationItem.rightBarButtonItem
}
@IBAction func searchButtonPressed(sender: AnyObject) {
showSearchBar()
}
func showSearchBar() {
searchBar.alpha = 0
navigationItem.titleView = searchBar
navigationItem.setLeftBarButtonItem(nil, animated: true)
UIView.animateWithDuration(0.5, animations: {
self.searchBar.alpha = 1
}, completion: { finished in
self.searchBar.becomeFirstResponder()
})
}
func hideSearchBar() {
navigationItem.setLeftBarButtonItem(searchBarButtonItem, animated: true)
logoImageView.alpha = 0
UIView.animateWithDuration(0.3, animations: {
self.navigationItem.titleView = self.logoImageView
self.logoImageView.alpha = 1
}, completion: { finished in
})
}
//MARK: UISearchBarDelegate
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
hideSearchBar()
}
}
这篇关于如何设置动画在UINavigationBar的顶部添加UISearchBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!