Showing posts with label uisearchcontroller. Show all posts
Showing posts with label uisearchcontroller. Show all posts

Tuesday, March 13, 2018

UITableView jumps between positions when activating and deactivating UISearchController

Leave a Comment

I've recently added a UISearchController to my table view and I'm experiencing an animation issue. When the search bar is tapped and becomes active, the table view jumps up to meet the search controller's new (active) position. The problem with this is that the search controller animates to this new position but the table view doesn't so it's quite jarring. Here is a video of the issue.

The top constraint on the table view is set to the view controller's safe area. Below is the code I have written for configuring the search controller:

- (void)configureSearchController {     UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];     searchController.searchResultsUpdater = self;     searchController.obscuresBackgroundDuringPresentation = NO;     searchController.searchBar.placeholder = @"Search for any cryptocurrency";     self.searchController = searchController;     if (@available(iOS 11.0, *)) {         self.navigationItem.searchController = searchController;     } else {         self.navigationItem.titleView = searchController.searchBar;     }     self.definesPresentationContext = YES; } 

Does anyone have any suggestions as to how I can make the transition smooth? Ideally I would like the table view to move up at the same rate as the search controller as this is the default behaviour throughout iOS.

2 Answers

Answers 1

I think, the problem with top constraint to safe area. SearchController couldn't update tableview frame while updating it's navigation bar position. So If you could set the tableview's top constraint to superview, animation could be smooth. Set your tableview constraints as below:

enter image description here

Hopefully, It will work!

Answers 2

From the video I believe the table view is not extending beneath the navigation bar. You can probably avoid that jump if you actually allow it to do so.

You should also set

tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic

So that its contentInsets are automatically adjusted.

Read More

Thursday, February 1, 2018

iOS - ScopeBar overlaps SearchBar in UISearchController in TabBarController

Leave a Comment

I am running into a peculiar issue regarding a scope bar shown under my UISearchBar. Basically, the issue I previously had was that whenever my UISearchController was active and the user switched tabs, if he came back to the UIViewController containing the UISearchController, the background would turn back. This issue was solved by embedding the UIViewController into a UINavigationController.

Now, a new issue has appeared. When I switch tabs with the UISearchController already active, when I switch back, the UIScopeBar is displayed on top of the UISearchBar. This can only be fixed by Canceling the search, and starting over.

Illustration: enter image description here

I have tried hiding the following code:

-(void)viewWillAppear:(BOOL)animated{ if(self.searchController.isActive){     [self.searchController.searchBar setShowsScopeBar:TRUE]; } }  -(void)viewDidDisappear:(BOOL)animated{     if(self.searchController.isActive){         [self.searchController.searchBar setShowsScopeBar:FALSE];     } } 

To no avail. If anybody has a trick for this one, I'd be glad to try it out.

1 Answers

Answers 1

Setting a constraint programatically each time you generate the view and come back to that tab might do the trick by keeping the UIScopeBar at a fixed distance from the top. You can also try setting the contraint between UIScopeBar and UISearchBar.

NSLayoutConstraint *topSpaceConstraint = [NSLayoutConstraint constraintWithItem:self.view                                                                              attribute:NSLayoutAttributeTop                                                                              relatedBy:NSLayoutRelationEqual                                                                                 toItem:UIScopeBar                                                                               attribute:NSLayoutAttributeTop                                                                             multiplier:1.0                                                                               constant:5.0]; [self.view addConstraint:topSpaceConstraint]; 

If this does not do the trick, you'll need to provide more code for me/people here to replicate the bug you're having.

Read More

Friday, January 26, 2018

Custom animation for UISearchController?

Leave a Comment

I'm presenting a UISearchController from my controller embedded in a navigation controller. The default animation occurs, where the search box drops down from the top on the navigation bar:

enter image description here

This isn't a good UX in my case because I present the search when a user taps into a UITextField in the middle of the screen. What I'd like to do is have the UITextField float to the top and morph into the search box, but I can't figure how to do this.

This is what I have:

class PlacesSearchController: UISearchController, UISearchBarDelegate {      convenience init(delegate: PlacesAutocompleteViewControllerDelegate) {          let tableViewController = PlacesAutocompleteContainer(             delegate: delegate         )          self.init(searchResultsController: tableViewController)          self.searchResultsUpdater = tableViewController         self.hidesNavigationBarDuringPresentation = false         self.definesPresentationContext = true         self.searchBar.placeholder = searchBarPlaceholder     } }  private extension ShowAddressViewController {      @objc func streetAddressTextFieldEditingDidBegin() {         present(placesSearchController, animated: true, completion: nil)     } } 

You can actually download and run the sample app that does this: https://expirebox.com/download/a105093cea111da24b310a35179e04dc.html

Instead of the search dropping down from the top, I'm hoping to get the text field fly up to the nav bar. What I’m after is the same effect that’s on the iOS 11 File app:

enter image description here

It has a text field in the middle of the screen then animated up to the nav bar when you tap on it. In my case tho, the text field is way lower in the screen and not originally part of the nav bar.

3 Answers

Answers 1

UISearchController

UISearchController is a component that highly difficult to customize. From my experience I can say, that it is better to use it as is without any drastic or significant customization. Otherwise, customization could result in messy code, global state variables, runtime tricks with UIView hierarchy etc. If specific behavior still needed, it is better to implement search controller from scratch or use third party one.

Default implementation

Looks like UISearchController was designed to be used in couple with UITableView and UISearchBar installed in the table header view. Even apple official code samples and documentation provides such example of usage (see UISearchController). Attempt to install UISearchBar somewhere else often results in numerous ugly side effects with search bar frame, position, twitching animations, orientation changes etc.

Starting with iOS 11, UINavigationItem got searchController property. It allows to integrate search controller into your navigation interface, so search will look exactly like iOS Files or iOS AppStore app. UISearchController's behavior still coupled with another component, but I believe it is better than coupling with UITableView all the time.

Possible solutions

From my perspective there are several possible solutions for your problem. I will provide them in order of increasing effort, which is needed for implementation:

  1. If you still want to use UISearchController, consider to use it as is without significant customizations. Apple provides sample code, that demonstrates how to use UISearchController (see Table Search with UISearchController).
  2. There are several third party libraries which may be more flexible with lots of additional features. For example: YNSearch, PYSearch. Please, have a look.
  3. Along with UISearchController presentation, you could try to move UITextField up with changing alpha from 1 to 0. This will create a feeling that UITextField is smoothly transforming to UISearchBar. This approach described in article that was provided by Chris Slowik (see comment to your original post). The only thing I would improve is animations using transition coordinators (see example here), it will make animations smoother with synchronized timing. Final implementation also will be much cleaner.
  4. As an option, you could try to design your own search controller using only UISearchBar or even plain UITextField.
  5. You could subclass UISearchController and add UITextField object. UISearchController conforms to UIViewControllerAnimatedTransitioning and UIViewControllerTransitioningDelegate protocols, where UITextFiled could be removed or added along with transition animations.

I hope this helps.

Update:

I have implemented approach I described under point 3. Here is how it works:

UISearchController with UITextField

You can find code snippet here. Please note, that it is only code example, there are might be situations which are not handled. Check it twice then.

Answers 2

  1. Create one UIView in XIB. name it searchView.
  2. Add UIButton inside above UIView in same xib and name it btnSearch. Like below in your scenario you have added textfield which is not mendetary

  3. Setup search controller in ViewDidLoad as below:

    func setupSearchController()  {   self.searchController = UISearchController(searchResultsController: nil)   self.searchController.delegate = self   self.searchController.searchBar.delegate = self   definesPresentationContext = true   self.searchController.dimsBackgroundDuringPresentation = false   self.searchController.searchBar.sizeToFit()   searchView.addSubview(self.searchController.searchBar)   self.searchController.searchBar.isHidden = true   self.searchController.searchBar.tintColor = UIColor.white   self.searchController.searchBar.showsCancelButton = false   UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = session?.makeColor(fromHexString: TYPE_COLOR, alpha: 1.0)   self.searchController.searchBar.isTranslucent = false   self.searchController.searchBar.barTintColor = UIColor(red: 239.0 / 255.0, green: 135.0 / 255.0, blue: 1.0 / 255.0, alpha: 1.0) } 

    This method will setup searchcontroller programatically inside searchview.

  4. Now you just need to show searchcontroller programatically. add On click method of button in step 2. Call this below method name showsearchAnimation:

    func ShowSeachAnimation() {   searchFrame = searchView.frame (add one global variable "searchFrame" in controller which saves searchView.frame so it will be used when cancel button clicked on search)   self.btnSearch.isHidden = true           var yAxis : CGFloat = 20   if #available(iOS 11 , *) {      yAxis = 8   } else  {      yAxis = 20   }   searchView.translatesAutoresizingMaskIntoConstraints = true   searchView.frame = CGRect(x: 0, y: yAxis, width: view.frame.size.width, height: view.frame.size.height - yAxis)    self.searchController.searchBar.isHidden = false   self.searchController.searchBar.becomeFirstResponder()   self.searchController.searchBar.showsCancelButton = true   self.searchBar(self.searchController.searchBar, textDidChange: "")   searchView.layoutIfNeeded() } 
  5. For hide searchbar, Add search hide method named "searchbarcancelbuttonclicked" in searchcontroller delegate:

    func searchViewHideAnimation()  {   self.removeNavigationBar()   self.navigationController?.isNavigationBarHidden = false   self.searchController.searchBar.text = " "   self.searchController.searchBar.isHidden = true   UIView.animate(withDuration: 0.3, animations: {() -> Void in       self.searchView.frame = self.searchFrame!       self.btnSearch.isHidden = false   }, completion: {(_ finished: Bool) -> Void in       self.searchView.layoutIfNeeded()   }) } 

Answers 3

you can try to use my https://github.com/Blackjacx/SHSearchBar Which essentially will be your text field. You can add constraints to the left, right and top and adjust the top constraint when the text field editing begins. At the same time, you hide the navigation bar animated and gray out the background by using an overlay view. This way you have maximized control over your animations and this appüroach is not so difficult as it might sound.

Read More

Sunday, December 3, 2017

UISearchController does not display as expected

Leave a Comment

I'm trying to add a UISearchController to a UIViewController that contains a UITableView (and an MKMapView too, but hopefully that's not the problem). I followed Ray Wenderlich's tutorial but I can't get the same result in terms of behaviour.

Here is my viewDidLoad:

override func viewDidLoad() {         super.viewDidLoad()          // Setup the Search Controller         searchController.searchResultsUpdater = self         searchController.obscuresBackgroundDuringPresentation = false         searchController.searchBar.placeholder = NSLocalizedString("Search references by project, customer or city", comment: "")         if #available(iOS 11.0, *) {             navigationItem.searchController = searchController             navigationItem.hidesSearchBarWhenScrolling = true         } else {             tableView.tableHeaderView = searchController.searchBar         }         definesPresentationContext = true          self.modeSelector.layer.cornerRadius = 5.0          if let split = splitViewController {             let controllers = split.viewControllers             detailViewController = (controllers[controllers.count - 1] as! UINavigationController).topViewController as? ReferenceViewController         }          self.navigationItem.rightBarButtonItem?.isEnabled = false     } 

Note that the #available test in the middle is because I need to support iOS up to 9.1.

Now I see several problems:

  • The search bar appears right away and I can't hide it by scrolling
  • When I focus the search bar, the top of the tableview doesn't stick to the bottom of the navigation item:

enter image description here

The only major difference I see with Ray Wenderlich's sample project is that since I created my project with XCode 9, my storyboard doesn't use top and bottom layout guides, but safe areas. Don't know if it's relevant, but that's the only thing I see.

Any idea what's going on and how I could fix this?

4 Answers

Answers 1

use this below line of code into your viewDidload

self.navigationController?.navigationBar.isTranslucent = false 

Hope this will help you

Answers 2

If you are using xcode 9 (ios 11). Then the thing you really want to do is - Use the new Broader navigation bars which are the new highlights in the ios 11 devices. But as there are many who have not shifted to ios-11, previous version devices are also taken into consideration. For adding the search bar to the newer navigation bars I have used the following function which gives a search bar on scrolling and hides it when user scrolls the page.

func addSearchBar() { if #available(iOS 11.0, *) {   let sc = UISearchController(searchResultsController: nil)   sc.delegate = self   let scb = sc.searchBar   scb.tintColor = UIColor.white   scb.barTintColor = UIColor.white   //Change the colors as you like them   if let textfield = scb.value(forKey: "searchField") as? UITextField {     textfield.textColor = UIColor.blue     if let backgroundview = textfield.subviews.first {        // Background color       backgroundview.backgroundColor = UIColor.white        // Rounded corner       backgroundview.layer.cornerRadius = 10;       backgroundview.clipsToBounds = true;     }   }    if let navigationbar = self.navigationController?.navigationBar {     navigationbar.barTintColor = UIColor.white   }   navigationItem.searchController = sc   navigationItem.hidesSearchBarWhenScrolling = true }else{ //add the logic for previous version devices here. } 

I have also set the self.navigationController?.navigationBar.prefersLargeTitles = true; in viewDidLoad as there is a bug in xcode9 and setting it from the interface builder does not work(yet).

The following method has been taken from here

Answers 3

I think that is your section header that is showing up blank. Try setting the heightForHeaderInSection as 0 and return nil for the viewForHeaderInSection.

Answers 4

If you need to support iOS up to 9.1, you probably use emulator with version older than 9.1. Therefore, "maybe" obscuresBackgroundDuringPresentation doesn't affect the searchController properly, since it's only available on iOS 9.1 or newer. Add dimsBackgroundDuringPresentation to support up to 9.1:

if #available(iOS 9.1, *) {     searchController?.obscuresBackgroundDuringPresentation = false } else {     searchController?.dimsBackgroundDuringPresentation = false } 

If this doesn't help to display as expected, I'm almost sure that the problem is about your layout constraints. Please add your current constraints if you couldn't bring your layout in compliance with safe area.

Read More

Monday, October 2, 2017

UISearchBarController iOS 11 issue - SearchBar and scope buttons overlap

Leave a Comment

Referred here and here. No answer in first link. In the second link, though the answer is not accepted, but the link to apple developer forum gives error.

Before iOS 11 :

enter image description here

iOS 11 :

enter image description here

Note : Same device same code.
Also, this would mean, all apps using this feature have to be republished ?

1 Answers

Answers 1

In the radar that Ray Wenderlich filed, @benck posted this answer from WWDC, which, if I'm not mistaken, hasn't been posted yet.

Read More

Sunday, October 1, 2017

How to lock UISearchBar in place to superview

Leave a Comment

I am using the UISearchController alongside its UISearchBar. The UISearchController alongside its UITableView is placed inside a subview in my main view.

My goal is to lock the UISearchBar in its place so when its active, it does not move. Right now the following is happening:

enter image description here enter image description here

I have searched this issue extensively and have tried the following such as:

  1. self.searchController.hidesNavigationBarDuringPresentation = false, which just abruptly moves the search bar to the middle of the screen.

  2. definesPresentationContext = true, which does not change behavior

  3. self.extendedLayoutIncludesOpaqueBars = true, which does not change behavior

  4. Using the UIBarPositioningDelegate method mentioned here, which strangely cannot be translated to Swift because I cannot insert the AnyObject<UIBarPositioning> as it is in the Objective C version and still have it recognized as the override function

Any suggestion is appreciated.

Edit:

Here is the setup for the search items:

    searchController.searchResultsUpdater = self     searchController.dimsBackgroundDuringPresentation = false     definesPresentationContext = true     searchTableView.tableHeaderView = searchController.searchBar 

1 Answers

Answers 1

Set your TableView's Style property to Plain in the Storyboard and use the SearchBar as the section header view. Along with the following code, I commented out tableView.tableHeaderView = searchController.searchBar in Apple's "Table Search with UISearchController" example and it worked fine.

override func numberOfSections(in tableView: UITableView) -> Int {     return 1 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {     return searchController.searchBar.frame.size.height } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {     return searchController.searchBar } 
Read More

Monday, March 28, 2016

Warning: Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted with “UISeachController”

Leave a Comment

To visualize - I've got the main view controller embedded in a UINavigationController and on this view controller the UISearchController is installed. After performing the search tapping a row on the table view containing the search results, it segues the user to the next view controller. Then on pressing the back button I get this warning. This doesn't happen on the iPad, only iPhone. The bigger picture is that the UINavigationController is the detail view controller of a UISplitViewController.

This is the implementation of the UISearchController

    func initializeSearchController() {         searchController = UISearchController(searchResultsController: nil)         writersTableView.tableHeaderView = searchController.searchBar         searchController.searchBar.barTintColor = UIColor.whiteColor()          searchController.searchBar.tintColor = UIColor.blackColor()         searchController.searchBar.scopeButtonTitles = ["All", "Favorites"]         searchController.searchBar.placeholder = "Search writers"          searchController.searchResultsUpdater = self         searchController.searchBar.delegate = self         searchController.delegate = self          definesPresentationContext = true         searchController.dimsBackgroundDuringPresentation = false         searchController.hidesNavigationBarDuringPresentation = true          searchController.searchBar.sizeToFit()         searchController.loadViewIfNeeded()     } 

Then there is another thing. I set the title of the second view controller dynamically according to which search result row is tapped like this: title = writer.name - The back button gets reset to whatever the value of the title of the second view controller is - and the title 'in the middle of the navigation bar' is left out blank. What I would like to have is the back button as it is and the second view controller title changes dynamically.

As indicated this doesn't happen with the iPad - Only iPhone?

0 Answers

Read More