UISearchDisplayController - how to preload searchResultTableView - ios

I want to show some default content when the user taps the Searchbar, but before any text is entered.
I have a solution working using settext:
- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
[searchDisplayController.searchBar setText:#" "];
}
This works but it's not elegant and the hint text in the Searchbar disappears.
Is there a better way to preload data to the SearchResultTableView in a UISearchDisplayController, without having to implement the whole UISearch functionality yourself in a custom controller?
For a demo of the desired effect, look at Safari's search box, if you tap it, the search interface opens with previous searches showing.

OK, I have it. Preload your dataSource with some data and do the following hack (nothing illegal) and you'll get the tableView to show up. Note that there may be some clean-up to do, but this will get your default data to display.
In viewDidLoad of the view controller than owns the UISearchBar:
[super viewDidLoad];
[self.searchDisplayController.searchResultsTableView reloadData];
// whatever you named your search bar - mine is property named searchBar
CGRect testFrame = CGRectMake(0, 20, self.searchBar.frame.size.width, 100);
self.searchDisplayController.searchResultsTableView.frame = testFrame;
[self.searchBar.superview addSubview:self.searchDisplayController.searchResultsTableView];
Here's what's happening:
The UISearchBar doesn't want to show the searchResultsTableView until you start editing. If you touch the tableView (e.g. reloadData) it will load and be there, sitting in memory with frame = CGRectZero. You give it a proper frame and then add it to the superview of the searchBar, et voila.
I verified this is correct by displaying the superview of the searchBar and the superview of the tableView after a proper load of the tableView - they have the same superview. So, I go back and add the tableView to the superview early, and sure enough it shows up. For me, it showed up dimmed (maybe another view above it? alpha set lower?), but was still clickable. I didn't go any further, but that definitely gets you your tableView displaying without any user interaction.
Enjoy,
Damien

I found a much better solution to this issue, and it seems to work perfectly on iOS 6 and 7. While it is still a hack, its a much cleaner and future proof hack than the above. The other solutions do not work consistently and prevent some UISearchDisplayDelegate methods from ever firing! Further I had complex insetting issues which I could not resolve with the above methods. The main issue with the other solutions is that they seriously confuse the internals of the UISearchDisplayController. My solution is based on the observation that UISearchDisplayContoller is a UISearchbarDelegate and that the automatic undimming & showing of results table can be triggered by simulating a keypress in the search field! So:
- (void) searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
if ([controller respondsToSelector: #selector(searchBar:textDidChange:)])
[(id<UISearchBarDelegate>)controller searchBar: controller.searchBar textDidChange: #" "];
}
This code is future proof against crashing by checking it responds to the UISearchbarDelegate method, and sends space #" " to trick the UISearchDisplayController into thinking user has typed a letter.
Now if the user types something and then erases it, the table will dim again. The other solutions try to work around this by doing something in the searchDisplayController:didHideSearchResultsTableView: method. But this doesn't make sense to me, as surely when you cancel the search it will need to truly hide your results table and you may need to run code in this case. My solution for this part is to subclass (note you could probably use a Method Swizzled Category to make it work everywhere if needed in your project):
// privately declare protocol to suppress compiler warning
#interface UISearchDisplayController (Super) <UISearchBarDelegate>
#end
// subclass to change behavior
#interface GMSearchDisplayController : UISearchDisplayController
#end
#implementation GMSearchDisplayController
- (void) searchBar: (UISearchBar *) searchBar textDidChange: (NSString *) searchString
{
if (searchString.length == 0)
searchString = #" ";
if ([super respondsToSelector: #selector(searchBar:textDidChange:)])
[super searchBar: searchBar textDidChange: searchString];
}
#end
This code works by intercepting the textDidChange delegate method and changing nil or empty strings in to space string #" " preventing the normal hiding/dimming that occurs on an empty search bar. If you are using this second bit of code, then you could modify the first bit to pass a nil instead of #" " as this second bit will do the needed conversion to #" " for you.
In my own project, I needed to handle the case that user does type a space, so instead of #" " above I used a defined token:
// arbitrary token used internally
#define SEARCH_PRELOAD_CONDITIONAL #"_#preresults#_"
And then handle it internally by converting it back to nil string:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
if ([searchString isEqualToString: SEARCH_PRELOAD_CONDITIONAL])
searchString = nil;
}
Enjoy! :)

Working solution for iOS 7:
// When the tableView is hidden, put it back
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
[self.searchDisplayController.searchResultsTableView reloadData];
controller.searchResultsTableView.hidden = NO;
// Also, remove the dark overlay
for (UIView *v in [[controller.searchResultsTableView superview] subviews]) {
// This is somewhat hacky..
if (v.alpha < 1) {
[v setHidden:YES];
}
}
}
-(void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView {
[self.searchDisplayController.searchResultsTableView reloadData];
if (self.searchDisplayController.active == YES) {
tableView.hidden = NO;
}
}

I have the solution. Insert these three methods.You have to have the tableview preloaded with the data in order this to work. I have this codes working in my code so it has to work for you as long as you have already preloaded the data and you are using search display controller.
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
CGRect testFrame = CGRectMake(0, self.notesSearchBar.frame.size.height, self.notesSearchBar.frame.size.width, self.view.frame.size.height - self.notesSearchBar.frame.size.height);
self.searchDisplayController.searchResultsTableView.frame = testFrame;
[self.notesSearchBar.superview addSubview:self.searchDisplayController.searchResultsTableView];
// [self.view addSubview:self.searchDisplayController.searchResultsTableView];
controller.searchResultsTableView.hidden = NO;
}
-(void) searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView
{
CGRect testFrame = CGRectMake(0, self.notesSearchBar.frame.size.height, self.notesSearchBar.frame.size.width, self.view.frame.size.height - self.notesSearchBar.frame.size.height);
self.searchDisplayController.searchResultsTableView.frame = testFrame;
[self.notesSearchBar.superview addSubview:self.searchDisplayController.searchResultsTableView];
// [self.view addSubview:self.searchDisplayController.searchResultsTableView];
controller.searchResultsTableView.hidden = NO;
}
-(void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
controller.searchResultsTableView.hidden = YES;
}

This works in iOS 8:
- (void)searchDisplayController:(UISearchDisplayController *)controller didHideSearchResultsTableView:(UITableView *)tableView
{
self.searchDisplayController.searchResultsTableView.hidden = NO;
}
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
self.searchDisplayController.searchResultsTableView.hidden = NO;
[self.searchDisplayController.searchResultsTableView.superview.superview bringSubviewToFront:self.searchDisplayController.searchResultsTableView.superview];
CGRect frame = self.searchDisplayController.searchResultsTableView.frame;
self.searchDisplayController.searchResultsTableView.frame = CGRectMake(frame.origin.x, 64, frame.size.width, frame.size.height);
}
However, I did not like this hack and replaced the searchDisplayController by my own implementation (UISearchBar with UITableView).

I tested the following in iOS 9 with UISearchController.
By default, whenever there is no text in the UISearchBar, the table shown will be your original table view (referred to as originalTableView from here on out). This may or may not have a black see-through layer depending on the value of dimsBackgroundDuringPresentation.
Once the user enters any text into the UISearchBar, the contents of the new table view will be shown (I will refer to this as the searchTableView).
Note that in both of these solutions, I'm implementing the UISearchController in a manner similar to how Apple does so in this example; namely, there are two separate UITableViewController's in charge of showing the data.
Solution 1: Complicated implementation, smoother animation
For a smoother animation:
Implement the UISearchControllerDelegate's willPresentSearchController and willDismissSearchController methods.
In willPresent, update your originalTableView's data to get ready to display whatever zero text data you want, then call reloadData().
In willDismiss, revert the process to show the original contents and call reloadData().
Example:
// here tableView refers to originalTableView
extension ViewController: UISearchControllerDelegate {
func willPresentSearchController(searchController: UISearchController) {
data = ["A", "B", "C"]
tableView.reloadData()
}
func willDismissSearchController(searchController: UISearchController) {
data = ["a", "b", "c"]
tableView.reloadData()
}
}
In this fictional example, the data is displayed as a,b,c when the user is not focused on the UISearchBar, but is displayed as A,B,C once the user taps on the UISearchBar.
Solution 2: Quick to implement, choppy animation
Instead of implementing the logic for the search controller in both originalTableView and searchTableView, you can use this solution to simply show the searchTableView even though it is hidden by default.
Most likely, you are already implementing the UISearchResultsUpdating protocol. By simply calling tableView.hidden = false in that method, you should get the behavior you are after; albeit with a less than stellar animation.
// here tableView refers to searchTableView
extension SearchViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
tableView.hidden = false
filterData(text: searchController.searchBar.text!)
tableView.reloadData()
}
}

Why don't you have a look at the TableSearch project that comes in Xcode? It more or less address what you need. It shows a table right at the beginning and shades it out when search field is tapped. Check TableSearch in Documentation and API reference in Xcode 4 under help.
Also take a look at this It almost does what you need with a UISearchBar and a UITableView. I'd prefer that approach instead. Tweak it.
And to address your needs further, I'd suggest using two datasources. One holding all the contents (this is what you would show at the very beginning) and one to hold the filtered search results. Now go ahead and empty the first datasource and fill it up with the contents of the second one to store & dim-show the results of the previous search. Proceed this way. Use this approach in the TableSearch code for your task.

Here's a way to pre-populate the searchController.
// 1. Save previous search results as soon as user enters text
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
// save searchString
return YES;
}
// 2. load previous search string at startup
- (void)viewDidLoad
{
// create data source for table view
// searchData may be a NSMutableArray property defined in your interface
self.searchData = // search your master list for searchString
// or create your own list using any search criteria you want
// or you may act depending on user preference
if(!showPreviousSearch)
{
// [searchData removeAllObjects];
}
}
// 3. provide correct data source when asked
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
...
}
NSMutableArray *dataSource = nil;
if (tableView == [[self searchDisplayController] searchResultsTableView])
{
dataSource = self.searchData;
}
else
{
dataSource = self.masterData;
}
...
return cell;
}
// Hope this helps.
Thanks

Related

UISearchBar textDidChange creating error: There are visible views left after reusing them all: { (null) = (null); }

I'm using a UITableViewController with a UISearchBar. Everything seems to work fine, except I'm getting a strange warning in the textDidChange method that I've never seen before.
This is my code:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[self.searchResults removeAllObjects];
if([searchText isEqualToString:#""]||searchText==nil){
[self.tableView reloadData];
return;
}
for(NSArray *monsterArray in self.monsterArray) {
NSString *name = monsterArray[0];
NSRange r = [[name lowercaseString] rangeOfString:[searchText lowercaseString]];
if(r.location != NSNotFound) {
if(r.location==0) {
[self.searchResults addObject:monsterArray];
}
}
}
[self.tableView reloadData];
}
By stepping through the program, I've found that the warning occurs right before the end of textDidChange. As I mentioned in the title, the warning is this:
There are visible views left after reusing them all: {
(null) = (null);
}
Does anyone know why this is happening, and how to resolve it?
I had a similar issue with a section header view with a custom UITextField. I got rid of the warning by calling resignFirstResponder on the text field before reloading the table view data, and calling becomeFirstResponder after the reload operation. Something like:
// Workaround: hide and show keyboard to prevent warning when reloading results
[self.searchTextField resignFirstResponder];
[self.tableView reloadData];
[self.searchTextField becomeFirstResponder];
While the other answer did get rid of the error being put in the console it also had some unintended consequences. Mainly calling resignFirstResponder and then becomeFirstResponder like that resets the state of the keyboard. So if you type a letter, the keyboard resets to Alpha from Numeric. This becomes annoying if you're trying to type a string of letters.
In my case I found the There are visible views left after reusing them all: { (null) = (null); } error was only logged when I had my UISearchBar set to the TableView's section header. I was doing this to keep the search bar floating at top of a UITableViewController.
Instead I refactored to use a UIViewController, placed the UISearchBar at the top and the UITableView under it this seems to have properly fixed the problem.

Drag and drop from Collectionview into ContactViewController doesn't work on iPad

I'm developing an app which uses splitView.
I'm using two items in splitView (Called them Customer and Supplier).
When I click on one of them I just use one viewController to display (called it: ContactViewController) and I use collectionView to display its data. To get data I just code it:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (!dbManager.synchronized) {
if (contactType == ContactTypeCustomer)
[dbManager requestData:kDbCustomers predicate:nil target:self];
else if (contactType == ContactTypeSuppplier)
[dbManager requestData:kDbSuppliers predicate:nil target:self];
}
}
And when get successful:
#pragma mark
#pragma DBDelegate
- (void)requestDataCompleted:(NSMutableArray *)results
{
datasource = results;
[self.collectionView reloadData];
}
I use I3DragBetweenHelper downloaded from github.com
Embedded into my app to initial drag and drop. To do this, I call the below method into viewDidLoad of ContactViewController
- (void) initDragAndDrop
{
self.helper = [[I3DragBetweenHelper alloc] initWithSuperview:self.view
srcView:_collectionView
dstView:_collectionView];
self.helper.delegate = self;
self.helper.isDstRearrangeable = NO;
self.helper.isSrcRearrangeable = NO;
self.helper.doesSrcRecieveDst = NO;
self.helper.doesDstRecieveSrc = YES;
self.helper.hideDstDraggingCell = YES;
self.helper.hideSrcDraggingCell = NO;
}
The helper here is:
#property (strong, nonatomic) I3DragBetweenHelper *helper;
The problem is when I click on Supplier I can drag and drop the cell of collectionView into ContactViewController. Below method had called and worked:
- (BOOL)droppedOutsideAtPoint:(CGPoint)pointIn fromDstIndexPath:(NSIndexPath *)from
But when I click on Customer the above method doesn't call. I can't even drag my cell of collectionView into ContactViewController. Any help will appreciate.
Why is isDstRearrangeable set to NO ??? coz eventually you would grab something and drop it onto something ( dest ) and that something ( dest ) will be rearranged, am i wrong ??
does your drag and drop happen in the same place ?? ( i.e: UICollectionView )
if it does, then why do you have src as not rearrangeable ??? both your destination and src should be rearrangeable.
Try this and let me know how it goes :)
I dont know about this library but I think the problem is your srcView and dstView are the same. These should be different and must be either UITableView or UICollectionView.
If you are using UISplitViewController, its probably going to be the Master and Detail View Controllers used by the UISplitView

UICollectionView UseLayoutToLayoutNavigationTransitions with different datasources

I have two UICollectionView objects, that both have different source and delegate. I would like to achieve a "Photos app'esque" look with the transition, using UseLayoutToLayoutNavigationTransitions.
It doesn't work though. When I call the UseLayoutToLayoutNavigationTransitions it changes the layout, but not the content.
First picture is first collection view. A series of categories and the people contained in them.
Second picture is what I'd like the animation to end up in. A series of people within a certain category.
Last picture is what happens right now. Categories just get rearranged.
Have a look at http://www.objc.io/issue-12/collectionview-animations.html in the
Transitions Between UICollectionViewController Instances
section.
it basically shows you that you'll have to change the datasource and delegate manually by implementation of the navigation controller delegate methods:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([viewController isKindOfClass:[FJDetailViewController class]]) {
FJDetailViewController *dvc = (FJDetailViewController*)viewController;
dvc.collectionView.dataSource = dvc;
dvc.collectionView.delegate = dvc;
[dvc.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_selectedItem inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
}
else if (viewController == self){
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
}
}
Your problem is that during the transition iOS will change the datasource. See my answer to this question How to use useLayoutToLayoutNavigationTransitions in UICollectionView?
You can use the same pattern described there:
use UseLayoutToLayoutNavigationTransitions to get the layout changes
observe when the transition is done
set the datasource to the one you need at that point

How to use UISearchbar and Searchdisplaycontroller with multiple tableviews?

I am currently trying to add some search-functionality to my app, but there are some problems, when configuring this. I have a tab-based application with 3 tableviews and I want to add one searchbar for all tableviews. But it seems not that easy to set this up.
The first problem that occurs is that inside the Storyboard-Editor I only can add a separate searchbar to every tableview, but it is not possible to add searchbar to the tabBarController itself. So that the same searchbar is visible over all 3 tableviews.
The Second Problem then is, if I get this some how working, I have to setup a searchDisplayController with 3 different tableviews, but i can initialize a searchDisplayController with just one tableview.
What is the best approach of searching 3 different categories with one searchbar on an iPhone and are there any tutorials out there ? I was also looking at some other apps like facebook, and they are also searching just inside one tableview.
You can use three search display controllers as follows: have each vc on each tab implement a method (and declare it publicly) like this:
- (void)searchFor:(NSString *)string {
[self.searchDisplayController setActive:YES];
self.searchDisplayController.searchBar.text = string;
}
Each of those should implement this method:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
// do the search logic for my table
// set a badge on my tab indicating how many results I found
// then perform it on the other vcs:
NSMutableArray *otherVCs = [[self.tabBarController viewControllers] mutableCopy];
[otherVCs removeObject:self];
for (MyViewController *otherVC in otherVCs) {
[otherVC searchFor:searchString];
}
}
You might need to make sure all your other tab vcs are loaded (if you launch the app, visit just one tab and try this, the other vcs might not be ready. To do that, just insert this line in the loop to force the view to load: (void)[otherVC view];
(note - this answer presumes ARC)
there is a little Problem with this solution. It causes an infinite loop. The solution is that we have to proof if the view is visible or not.
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self setUpFilteredEndlessScrollingWithUrl:kGetAllTours];
[self loadFilteredDataWithPath:kGetAllTours];
if (self.isViewLoaded && self.view.window) {
NSMutableArray *otherVCs = [[self.tabBarController viewControllers] mutableCopy];
[otherVCs removeObject:self];
for (BaseTableViewController *otherVC in otherVCs) {
[otherVC searchFor:searchString];
}
}
return YES;
}

What is the correct usage of the UISearchBarDelegate showsSearchResultsButton attribute?

I configure my search bar to show the results button, but the button only shows until the user enters a character. At that point, the "X" cancel button replaces it. So without entering characters, the search result set equals the entire data set. I'd like the results button to stay there so when the user has typed enough characters to get a smaller result set (like 5 or 6 rows), they can click the results button, my delegate will get called, and I can show just that result set.
UISearchBar * theSearchBar = [[UISearchBar alloc]
initWithFrame:CGRectMake(0,0,700,40)];
theSearchBar.delegate = self;
theSearchBar.placeholder = #"What are you looking for?";
theSearchBar.showsCancelButton = NO; // shows up after first char typed.
theSearchBar.showsSearchResultsButton = YES; // disappears just when I need it.
...further down in the VC... this method can only called when the search bar's input field is empty.
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar {
NSLog(#" searchBarResultsListButtonClicked for %#",searchBar); //
}
Advice, tutorials, sample code and justified dope-slaps welcome.
TIA
-Mike
#Rayfleck, I think you should not worry about Search Results Button at all.
If what you need is to monitor user's input until they have entered enough characters for filtering:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if ([searchText length]>5) {
[self filterDataWithKeyword:searchText];
[self.tableView reloadData];
} else {
[self resetFilter];
[self.tableView reloadData];
}
}
Here is a partial answer that you can stick in viewDidLoad. It should hide the clear button, but it doesn't keep the results button visible. I'm not sure how the results button view logic is controlled behind the scenes.
for (id subview in mySearchBar.subviews) {
if ([[subview class] isSubclassOfClass:[UITextField class]]) {
[subview setClearButtonMode:UITextFieldViewModeNever];
break;
}
}
Since this approach uses all public APIs your app shouldn't get rejected. Although this approach might be prone to breaking further down the road if/when Apple decides to change the hierarchy of UISearchBar. All I'm doing is looking for the UITextField or subclass and setting its clearButtonMode.
Hope this helps.

Resources