下面的代码只是为了说明这个想法。如果你想使用它,你必须根据你的需要调整它,注意方向的变化并添加一个 tableView。还有一些常数可以用更好的东西代替。
class ViewController: UIViewController, UISearchBarDelegate {
let searchBar = UISearchBar()
private var searchBarVisible = false
override func viewDidLoad() {
super.viewDidLoad()
searchBar.showsCancelButton = true
searchBar.delegate = self
let height: CGFloat = 44
let window = UIApplication.sharedApplication().keyWindow!
self.searchBar.frame = CGRectMake(0, -height, window.frame.width, height)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.dismissSearchBarAnimated(true)
}
func showSearchBarAnimated(animated: Bool) {
if !searchBarVisible {
let window = UIApplication.sharedApplication().keyWindow!
window.addSubview(searchBar)
searchBar.setNeedsLayout()
let duration = animated ? 0.2 : 0 // 0 executes immediately
self.searchBar.becomeFirstResponder()
UIView.animateWithDuration(duration) { () -> Void in
self.searchBar.frame = CGRectMake(0, 20, window.frame.width, self.searchBar.frame.height)
}
searchBarVisible = true
}
}
func dismissSearchBarAnimated(animated: Bool) {
let window = UIApplication.sharedApplication().keyWindow!
let duration = animated ? 0.2 : 0 // 0 executes immediately
self.searchBar.resignFirstResponder()
UIView.animateWithDuration(duration,
animations: { () -> Void in
self.searchBar.frame = CGRectMake(0, -self.searchBar.frame.height, window.frame.width, self.searchBar.frame.height)
}) {(completed) -> Void in
self.searchBar.removeFromSuperview()
self.searchBarVisible = false
}
}
@IBAction func actionSearchButton(sender: AnyObject) {
self.showSearchBarAnimated(true)
}
//MARK: - UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
NSLog("Should search for '\(searchText)'.")
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
self.dismissSearchBarAnimated(true)
}
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached
}
}