Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search bar when swiping down in swift

I am developing a social media app for iOS

My ViewControllers are currently embedded in a NavigationController. On my news feed screen, I need to display a search bar when the user swipes down (and hide it when he swipes up) in which if the user types something, the search results will be displayed on top of the news feed screen.

I have tried to tinker with this but I am pretty new to iOS and so far have not managed to get this to work.

Any help would grately be appreciated and keep in mind that I have only been programming iOS for a couple of weeks so some in-depth would be helpful. Thank you !

like image 862
Dan Moldovan Avatar asked Oct 31 '14 10:10

Dan Moldovan


1 Answers

First, you'll need to implement UISwipeGestureRecognizer

include the setup() function in viewDidAppear

func setup() {
    let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(down))
    swipeDown.direction = .down
    let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(up))
    swipeUp.direction = .up

    self.view.addGestureRecognizer(swipeDown)
    self.view.addGestureRecognizer(swipeUp)

    searchBar = UISearchBar(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: 40.0))
    if let searchBar = searchBar
    {
        searchBar.backgroundColor = UIColor.red
        self.view.addSubview(searchBar)
    }
}

Then your two functions up and down

func down(sender: UIGestureRecognizer) {
    print("down")
    //show bar
    UIView.animate(withDuration: 1.0, animations: { () -> Void in
        self.searchBar!.frame = CGRect(x: 0.0, y: 64.0, width: self.view.frame.width, height: 40.0)
    }, completion: { (Bool) -> Void in
    })
}

func up(sender: UIGestureRecognizer) {
    print("up")
    UIView.animate(withDuration: 1.0, animations: { () -> Void in
        self.searchBar!.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: 40.0)
    }, completion: { (Bool) -> Void in
    })
}

You can add Bool isShowing to avoid unnecessary animations. Then, implement the search bar delegate textDidChange to change the search results as the user types.

func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String)`

All you need to do now is display your results in a UISearchController.

Note Using swipe up/down motion might interfere with the scrolling of the UIScreachController

like image 157
Laurent Rivard Avatar answered Sep 25 '22 10:09

Laurent Rivard