How To Provide Search-As-You-Type Filtering With UICollectionView? - uitextfield

I have a UICollectionView added to a ViewController. The UICollectionView displays a grid of items with peoples names on each cell.
I would like to add search as you type functionality that will filter the UICollectionView as the user types in their name to a searchbar or UITextField on the ViewController so that it doesn't scroll with the content in the UICollectionView.
Even though a few places I have read that UICollectionView is similar to UITableView I don't see that implementing this filter/search functionality is the same in UICollectionView as it is with UITableView and need some help with it.
Does anyone have a good example of doing this search/filter as you type functionality with UICollectionView?

I solved it by doing the following (hope it helps somebody else):
I populate my UICollectionView from CoreData into an NSArray:
self.allCVData = [context executeFetchRequest:fetchRequest error:&error];
then add my NSArray to an NSMutableArray so that I can use that for filtering on the UICollection:
self.filteredCVData = [[NSMutableArray alloc] initWithArray:allCVData];
Added a UITextField and called it searchField.
Added a selector in viewDidLoad:
[mytextfield addTarget:self action:#selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
Added a method to accept changes in the UITextField:
-(void) textDidChange:(id)sender
{
UITextField* searchField = (UITextField *) sender;
if(searchField.text.length == 0)
{
self.isFiltered = FALSE;
[self.filteredCVData removeAllObjects];
[self.filteredCVData addObjectsFromArray:self.allCVData];
}
else
{
self.isFiltered = true;
[self.filteredCVData removeAllObjects];
self.filteredCVData = [[NSMutableArray alloc] init];
LogInfo(#"Before Looping in allCVData Array.");
for (OLPerson* person in allCVData)
{
NSRange firstnameRange = [person.firstname rangeOfString:searchField.text options:NSCaseInsensitiveSearch];
NSRange surnameRange = [person.surname rangeOfString:searchField.text options:NSCaseInsensitiveSearch];
if(firstnameRange.location != NSNotFound || surnameRange.location != NSNotFound)
{
[self.filteredCVData addObject:person];
}
}
}
[self.collectionView reloadData];
}

Related

Xcode: iPad keyboard troubles (not that simple)

I am making an app which uses many Textfields. Most of them are inside static tableViews. I use the split view application template. Every category selected from the left panel presents a storyboard scene inside a second view on the right panel.
I just want to get rid of the keyboard with the "done" button however everything i have tried that would work on a simple view fails to work under these circumstances.
Can you please help me out with this?
p.s. I try to dismiss the keyboard inside the implementation file of the presented storyboard scene. Should i do something inside the Detail Scene of the split view controller?
Here is my Scene's code:
.h
#import <UIKit/UIKit.h>
#interface AfoEsoda : UITableViewController <UITextFieldDelegate>{
}
#property (strong, nonatomic) IBOutlet UITextField *merismataTF;
-(IBAction)hideKeyboard:(id)sender;
#end
.m
#synthesize merismataTF;
- (void)viewDidLoad
{
[super viewDidLoad];
merismataTF.delegate=self ;
}
//---------Hide Keyboard-------------------
//Tried but didn't work
-(IBAction)hideKeyboard:(id)sender {
[merismataTF resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
//Of course i do not use both methods at the same time.
EDIT:
When i set the textfield's delegate to self i get this crash:
Try implementing the textField's delegate, set the delegate to self, and in the delegate's method
- (BOOL)textFieldShouldReturn:(UITextField *)textField
set
[textField resignFirstResponder];
Another way could be going through all of the view's subviews and if it is a text field, resign first responder:
for(int i=0;i<self.view.subviews.count;i++)
{
if([[self.view.subviews objectAtIndex:i] isKindOfClass:[UITextField class]])
{
if([[self.view.subviews objectAtIndex:i] isFirstResponder])
[[self.view.subviews objectAtIndex:i] resignFirstResponder];
}}
OK, I got it. Use this with with the textFieldShouldReturn method.
So here is your answer: You have declared your text field as a property and then use alloc and init it over and over again for each cell. Probably it only works properly for the last row.
Here is an example of how your cellForRow method should look like:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ static NSString *cellIdentifier = #"My cell identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITextField *newTextField;
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
newTextField = [[UITextField alloc] initWithFrame:CGRectMake:(0,0,25,25)];
newTextField.tag = 1;
newTextField.delegate = self;
[cell.contentView addSubview:newTextField];
}
else
newTextField = (UITextField *)[cell.contentView viewWithTag:1];
And then, if you need the textField's value for a certaing row, simply use:
UITextField *someTextField = (UITextField *)[[tableView cellForRowAtIndexPath:indexPath].contentView viewWithTag:1];
NSLog(#"textField.text = %#", someTextField.text);

UIBarButtonItem frame? [duplicate]

UIBarButtonItem does not extend UIView, so there is nothing like a frame property.
But is there any way I can get what is it's CGRect frame, relative to the application UIWindow?
Do you like to use private APIs? If yes,
UIView* view = thatItem.view;
return [view convertRect:view.bounds toView:nil];
Of course no one wants this when targeting the AppStore. A more unreliable method, and also uses undocumented features, but will pass Apple's test, is to loop through the subviews to look for the corresponding button item.
NSMutableArray* buttons = [[NSMutableArray alloc] init];
for (UIControl* btn in theToolbarOrNavbar.subviews)
if ([btn isKindOfClass:[UIControl class]])
[buttons addObject:btn];
UIView* view = [buttons objectAtIndex:index];
[buttons release];
return [view convertRect:view.bounds toView:nil];
The index is the index to your bar item in the array of .items, after removing all blank items. This assumes the buttons are arranged in increasing order, which may not be. A more reliable method is to sort the buttons array in increasing .origin.x value. Of course this still assumes the bar button item must inherit the UIControl class, and are direct subviews of the toolbar/nav-bar, which again may not be.
As you can see, there are a lot of uncertainty when dealing with undocumented features. However, you just want to pop up something under the finger right? The UIBarButtonItem's .action can be a selector of the form:
-(void)buttonClicked:(UIBarButtonItem*)sender event:(UIEvent*)event;
note the event argument — you can obtain the position of touch with
[[event.allTouches anyObject] locationInView:theWindow]
or the button view with
[[event.allTouches anyObject] view]
Therefore, there's no need to iterate the subviews or use undocumented features for what you want to do.
I didn't see this option posted (which in my opinion is much simpler), so here it is:
UIView *barButtonView = [barButtonItem valueForKey:#"view"];
In iOS 3.2, there's a much easier way to show an Action Sheet popover from a toolbar button. Merely do something like this:
- (IBAction)buttonClicked:(UIBarButtonItem *)sender event:(UIEvent *)event
{
UIActionSheet *popupSheet;
// Prepare your action sheet
[popupSheet showFromBarButtonItem:sender animated:YES];
}
This is the implementation I use for my WEPopover project: (https://github.com/werner77/WEPopover):
#implementation UIBarButtonItem(WEPopover)
- (CGRect)frameInView:(UIView *)v {
UIView *theView = self.customView;
if (!theView.superview && [self respondsToSelector:#selector(view)]) {
theView = [self performSelector:#selector(view)];
}
UIView *parentView = theView.superview;
NSArray *subviews = parentView.subviews;
NSUInteger indexOfView = [subviews indexOfObject:theView];
NSUInteger subviewCount = subviews.count;
if (subviewCount > 0 && indexOfView != NSNotFound) {
UIView *button = [parentView.subviews objectAtIndex:indexOfView];
return [button convertRect:button.bounds toView:v];
} else {
return CGRectZero;
}
}
#end
As long as UIBarButtonItem (and UITabBarItem) does not inherit from UIView—for historical reasons UIBarItem inherits from NSObject—this craziness continues (as of this writing, iOS 8.2 and counting ... )
The best answer in this thread is obviously #KennyTM's. Don't be silly and use the private API to find the view.
Here's a oneline Swift solution to get an origin.x sorted array (like Kenny's answer suggests):
let buttonFrames = myToolbar.subviews.filter({
$0 is UIControl
}).sorted({
$0.frame.origin.x < $1.frame.origin.x
}).map({
$0.convertRect($0.bounds, toView:nil)
})
The array is now origin.x sorted with the UIBarButtonItem frames.
(If you feel the need to read more about other people's struggles with UIBarButtonItem, I recommend Ash Furrow's blog post from 2012: Exploring UIBarButtonItem)
I was able to get Werner Altewischer's WEpopover to work by passing up the toolbar along with the
UIBarButton:
Mod is in WEPopoverController.m
- (void)presentPopoverFromBarButtonItem:(UIBarButtonItem *)item toolBar:(UIToolbar *)toolBar
permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections
animated:(BOOL)animated
{
self.currentUIControl = nil;
self.currentView = nil;
self.currentBarButtonItem = item;
self.currentArrowDirections = arrowDirections;
self.currentToolBar = toolBar;
UIView *v = [self keyView];
UIButton *button = nil;
for (UIView *subview in toolBar.subviews)
{
if ([[subview class].description isEqualToString:#"UIToolbarButton"])
{
for (id target in [(UIButton *)subview allTargets])
{
if (target == item)
{
button = (UIButton *)subview;
break;
}
}
if (button != nil) break;
}
}
CGRect rect = [button.superview convertRect:button.frame toView:v];
[self presentPopoverFromRect:rect inView:v permittedArrowDirections:arrowDirections animated:animated];
}
-(CGRect) getBarItemRc :(UIBarButtonItem *)item{
UIView *view = [item valueForKey:#"view"];
return [view frame];
}
You can get it from the UINavigationBar view. The navigationBar is a UIView which has 2 or 3 custom subviews for the parts on the bar.
If you know that the UIBarButtonItem is currently shown in the navbar on the right, you can get its frame from navbar's subviews array.
First you need the navigationBar which you can get from the navigationController which you can get from the UIViewController. Then find the right most subview:
UINavigationBar* navbar = curViewController.navigationController.navigationBar;
UIView* rightView = nil;
for (UIView* v in navbar.subviews) {
if (rightView==nil) {
rightView = v;
} else if (v.frame.origin.x > rightView.frame.origin.x) {
rightView = v; // this view is further right
}
}
// at this point rightView contains the right most subview of the navbar
I haven't compiled this code so YMMV.
This is not the best solution and from some point of view it's not right solution and we can't do like follow because we access to object inside UIBarBattonItem implicitly, but you can try to do something like:
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[button setImage:[UIImage imageNamed:#"Menu_Icon"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(didPressitem) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.rightBarButtonItem = item;
CGPoint point = [self.view convertPoint:button.center fromView:(UIView *)self.navigationItem.rightBarButtonItem];
//this is like view because we use UIButton like "base" obj for
//UIBarButtonItem, but u should note that UIBarButtonItem base class
//is NSObject class not UIView class, for hiding warning we implicity
//cast UIBarButtonItem created with UIButton to UIView
NSLog(#"point %#", NSStringFromCGPoint(point));
as result i got next:
point {289, 22}
Before implement this code, be sure to call [window makeKeyAndVisible] in your Applition delegate application:didFinishLaunchingWithOptions: method!
- (void) someMethod
{
CGRect rect = [barButtonItem convertRect:barButtonItem.customview.bounds toView:[self keyView]];
}
- (UIView *)keyView {
UIWindow *w = [[UIApplication sharedApplication] keyWindow];
if (w.subviews.count > 0) {
return [w.subviews objectAtIndex:0];
} else {
return w;
}
}
I handled it as follows:
- (IBAction)buttonClicked:(UIBarButtonItem *)sender event:(UIEvent *)event
{
UIView* view = [sender valueForKey:#"view"]; //use KVO to return the view
CGRect rect = [view convertRect:view.bounds toView:self.view];
//do stuff with the rect
}

ipad: predictive search in a popover

I want to implement this
1) when user start typing in a textfield a popOver flashes and shows the list of items in a table view in the popover as per the string entered in textfield.
2) Moreover this data should be refreshed with every new letter entered.
kind of predictive search.
Please help me with this and suggest possible ways to implement this.
UISearchDisplayController does most of the heavy lifting for you.
Place a UISearchBar (not a UITextField) in your view, and wire up a UISearchDisplayController to it.
// ProductViewController.h
#property IBOutlet UISearchBar *searchBar;
#property ProductSearchController *searchController;
// ProductViewController.m
- (void) viewDidLoad
{
[super viewDidLoad];
searchBar.placeholder = #"Search products";
searchBar.showsCancelButton = YES;
self.searchController = [[[ProductSearchController alloc]
initWithSearchBar:searchBar
contentsController:self] autorelease];
}
I usually subclass UISearchDisplayController and have it be it's own delegate, searchResultsDataSource and searchResultsDelegate. The latter two manage the result table in the normal manner.
// ProductSearchController.h
#interface ProductSearchController : UISearchDisplayController
<UISearchDisplayDelegate, UITableViewDelegate, UITableViewDataSource>
// ProductSearchController.m
- (id)initWithSearchBar:(UISearchBar *)searchBar
contentsController:(UIViewController *)viewController
{
self = [super initWithSearchBar:searchBar contentsController:viewController];
self.contents = [[NSMutableArray new] autorelease];
self.delegate = self;
self.searchResultsDataSource = self;
self.searchResultsDelegate = self;
return self;
}
Each keypress in the searchbar calls searchDisplayController:shouldReloadTableForSearchString:. A quick search can be implemented directly here.
- (BOOL) searchDisplayController:(UISearchDisplayController*)controller
shouldReloadTableForSearchString:(NSString*)searchString
{
// perform search and update self.contents (on main thread)
return YES;
}
If your search might take some time, do it in the background with NSOperationQueue. In my example, ProductSearchOperation will call showSearchResult: when and if it completes.
// ProductSearchController.h
#property INSOperationQueue *searchQueue;
// ProductSearchController.m
- (BOOL) searchDisplayController:(UISearchDisplayController*)controller
shouldReloadTableForSearchString:(NSString*)searchString
{
if (!searchQueue) {
self.searchQueue = [[NSOperationQueue new] autorelease];
searchQueue.maxConcurrentOperationCount = 1;
}
[searchQueue cancelAllOperations];
NSInvocationOperation *op = [[[ProductSearchOperation alloc]
initWithController:self
searchTerm:searchString] autorelease];
[searchQueue addOperation:op];
return NO;
}
- (void) showSearchResult:(NSMutableArray*)result
{
self.contents = result;
[self.searchResultsTableView
performSelectorOnMainThread:#selector(reloadData)
withObject:nil waitUntilDone:NO];
}
It sounds like you have a pretty good idea of an implementation already. My suggestion would be to present a UITableView in a popover with the search bar at the top, then simply drive the table view's data source using the search term and call reloadData on the table view every time the user types into the box.

xcode Removing Some Subviews from view

Greetings all,
I am a noob and I have been trying to work through this for a few days.
I am adding images to a view via UItouch. The view contains a background on top of which the new images are add. How do I clear the images I am adding from the subview, without getting rid of the UIImage that is the background. Any assistance is greatly appreciated. Thanks in Advance.
here is the code:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event {
NSUInteger numTaps = [[touches anyObject] tapCount];
if (numTaps==2) {
imageCounter.text =#"two taps registered";
//__ remove images
UIView* subview;
while ((subview = [[self.view subviews] lastObject]) != nil)
[subview removeFromSuperview];
return;
}else {
UITouch *touch = [touches anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
CGRect myImageRect = CGRectMake((touchPoint.x -40), (touchPoint.y -45), 80.0f, 90.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:#"pg6_dog_button.png"]];
myImage.opaque = YES; // explicitly opaque for performance
[self.view addSubview:myImage];
[myImage release];
[imagesArray addObject:myImage];
NSNumber *arrayCount =[self.view.subviews count];
viewArrayCount.text =[NSString stringWithFormat:#"%d",arrayCount];
imageCount=imageCount++;
imageCounter.text =[NSString stringWithFormat:#"%d",imageCount];
}
}
What you need is a way of distinguishing the added UIImageView objects from the background UIImageView. There are two ways I can think of to do this.
Approach 1: Assign added UIImageView objects a special tag value
Each UIView object has a tag property which is simply an integer value that can be used to identify that view. You could set the tag value of each added view to 7 like this:
myImage.tag = 7;
Then, to remove the added views, you could step through all of the subviews and only remove the ones with a tag value of 7:
for (UIView *subview in [self.view subviews]) {
if (subview.tag == 7) {
[subview removeFromSuperview];
}
}
Approach 2: Remember the background view
Another approach is to keep a reference to the background view so you can distinguish it from the added views. Make an IBOutlet for the background UIImageView and assign it the usual way in Interface Builder. Then, before removing a subview, just make sure it's not the background view.
for (UIView *subview in [self.view subviews]) {
if (subview != self.backgroundImageView) {
[subview removeFromSuperview];
}
}
A more swiftly code for approach #1 in only one functional line of code :
self.view.subviews.filter({$0.tag == 7}).forEach({$0.removeFromSuperview()})

Clickable url link in NSTextFieldCell inside NSTableView?

I have a NSAttributedString that I'm using in a NSTextFieldCell. It makes several clickable url links and puts a big NSAttributedString inside the NSTextFieldCell. Whenever I am viewing the NSTextFieldCell normally and it's highlighted, I cannot click on the links.
If I set the TableView so I can edit each column or row, when I click twice, go into Edit mode and view the NSTextFieldCell contents, my links show up and are clickable. When I click away from the row, I can no longer see clickable links.
I have to be in "edit" mode to see the links or click on them.
I feel like there's some setting I'm just missing.
I don't think the tech note answers the question, which was how to put a link in an NSTableView cell. The best way I've found to do this is to use a button cell for the table cell. This assumes that only links will be in a particular column of the table.
In Interface Builder, drag an NSButton cell onto the table column where you want the links.
In your table view delegate, implement tableView:dataCellForTableColumn:row: as follows:
- (NSCell *) tableView: (NSTableView *) tableView
dataCellForTableColumn: (NSTableColumn *) column
row: (NSInteger) row
{
NSButtonCell *buttonCell = nil;
NSAttributedString *title = nil;
NSString *link = nil;
NSDictionary *attributes = nil;
// Cell for entire row -- we don't do headers
if (column == nil)
return(nil);
// Columns other than link do the normal thing
if (![self isLinkColumn:column]) // Implement this as appropriate for your table
return([column dataCellForRow:row]);
// If no link, no button, just a blank text field
if ((link = [self linkForRow:row]) != nil) // Implement this as appropriate for your table
return([[[NSTextFieldCell alloc] initTextCell:#""] autorelease]);
// It's a link. Create the title
attributes = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSFont systemFontOfSize:[NSFont systemFontSize]], NSFontAttributeName,
[NSNumber numberWithInt:NSUnderlineStyleSingle], NSUnderlineStyleAttributeName,
[NSColor blueColor], NSForegroundColorAttributeName,
[NSURL URLWithString:link], NSLinkAttributeName, nil];
title = [[NSAttributedString alloc] initWithString:link attributes:attributes];
[attributes release];
// Create a button cell
buttonCell = [[[NSButtonCell alloc] init] autorelease];
[buttonCell setBezelStyle:NSRoundedBezelStyle];
[buttonCell setButtonType:NSMomentaryPushInButton];
[buttonCell setBordered:NO]; // Don't want a bordered button
[buttonCell setAttributedTitle:title];
[title release];
return(buttonCell);
}
Set the target/action for the table to your delegate and check for clicks on the link column:
- (void) clickTable: (NSTableView *) sender
{
NSTableColumn *column = [[sender tableColumns] objectAtIndex:[sender clickedColumn]];
NSInteger row = [sender clickedRow];
NSString *link = nil;
if ([self isLinkColumn:column] && (link = [self linkForRow:row]) != nil)
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:link]];
}
Now the link looks like a link, but a click on it is actually a button press, which you detect in the action method and dispatch using NSWorkspace.
Have you seen this technical note from Apple regarding hyperlinks?
Embedding Hyperlinks in NSTextField and NSTextView

Resources