Saturday, August 10, 2013

Using TextField as UISearchBar and searching UIScrollView

The most awaited post I am writing . I solved as it was not available on the internet.

In demo.xib (.xib file) :-


Just add a textfield. And assign this text field to txt1.

In demo.h ( .h file):- 

//
//  ViewController.h
//  demo
//
//  Created by Ashish Maheshwari on 09/08/13.
//  Copyright (c) 2013 Ashish Maheshwari. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>

{
       IBOutlet UITextField *txt1;
    
    UIScrollView *scrollView;
    UIScrollView *scrollView1;
    
    // creating a search string
    
    NSString *strSearchData;
    
    // Creating arrays for the data 
    
    NSMutableArray *arr1;
    NSMutableArray *arr2;
    NSMutableArray *arr3;
    
    // mutable arrays to be used during search
    
    NSMutableArray *resultArrayId;
    NSMutableArray *resultArrayName;
    NSMutableArray *resultArrayImage;
    
    // creating dictionaries
    
    NSDictionary *dict1;
    NSDictionary *dict2;
    NSMutableDictionary *dict3;
    
    // creating arrays so that the data can be loaded on load in two images
    
    NSMutableArray *divideSuperId1;
    NSMutableArray *divideSuperId2;
    NSMutableArray *divideSuperImage1;
    NSMutableArray *divideSuperImage2;
    NSMutableArray *divideSuperName1;
    NSMutableArray *divideSuperName2;

}

@property(nonatomic,retain)NSMutableArray *resultArrayId;
@property(nonatomic,retain)NSMutableArray *resultArrayName;
@property(nonatomic,retain)NSMutableArray *resultArrayImage;
@property(nonatomic,retain)IBOutlet UITextField *txt1;
@property(nonatomic,retain)NSString *strSearchData;

@end

In demo.m (.m file):- 

//
//  ViewController.m
//  demo
//
//  Created by Ashish Maheshwari on 09/08/13.
//  Copyright (c) 2013 Ashish Maheshwari. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize resultArrayId,resultArrayImage,resultArrayName,strSearchData,txt1;

# pragma mark Generate Scroll View

-(void)Scroll:(NSMutableArray *)array1 name:(NSMutableArray *)array2 image:(NSMutableArray *)array3
{
    // dividing of array in two parts and showing on load
    
    [divideSuperId1 removeAllObjects];
    [divideSuperId2 removeAllObjects];
    [divideSuperImage1 removeAllObjects];
    [divideSuperImage2 removeAllObjects];
    [divideSuperName1 removeAllObjects];
    [divideSuperName2 removeAllObjects];
    
    
    NSLog(@"arr1= %@",array1);
    NSLog(@"arr2= %@",array2);
    NSLog(@"arr3= %@",array3);
    
    for (int i=0; i < [array1 count]; i=i+1) {
        double cnt=[array1 count];
        if (i < cnt/2) {
            [divideSuperId1 addObject:[array1 objectAtIndex:i]];
        }
        else {
            [divideSuperId2 addObject:[array1 objectAtIndex:i]];
        }
    }
    
    for (int i=0; i < [array3 count]; i=i+1) {
        double cnt=[array3 count];
        if (i < cnt/2) {
            [divideSuperImage1 addObject:[array3 objectAtIndex:i]];
        }
        else {
            [divideSuperImage2 addObject:[array3 objectAtIndex:i]];
        }
    }
    
    for (int i=0; i < [array2 count]; i=i+1) {
        double cnt=[array2 count];
        if (i < cnt/2) {
            [divideSuperName1 addObject:[array2 objectAtIndex:i]];
        }
        else {
            [divideSuperName2 addObject:[array2 objectAtIndex:i]];
        }
    }

  
    
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(5, 90,self.view.frame.size.width ,self.view.frame.size.height)];
    
    //    int numberOfImages = 5;
    CGFloat currentY1 = 0.0f;
    CGFloat currentY2 =0.0f;
    
    CGFloat lbCurrentY=0.0f;
    
    CGFloat h1;
    CGFloat h2;
    
    
    for (int i=0; i<[divideSuperId1 count]; i++)
    {
        
        // create image no. 1
        
       
        UIImage *image = [UIImage imageNamed:[divideSuperImage1 objectAtIndex:i]];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        
        
        CGRect rect = imageView.frame;
        CGFloat width=152;
        CGFloat height=imageView.frame.size.height/2.0;
        rect = CGRectMake(0, currentY1, width, height);
        imageView.frame = rect;
        
        // update currentY
        
        currentY1 += imageView.frame.size.height+5;
        h1=imageView.frame.size.height;
        
        //Puting image on Button 1
        UIButton *btnimage1=[UIButton buttonWithType:UIButtonTypeCustom];
        btnimage1.frame=rect;
        [btnimage1 setImage:imageView.image forState:UIControlStateNormal];
        btnimage1.tag=[[divideSuperId1 objectAtIndex:i]integerValue];
        NSLog(@"%d",btnimage1.tag);
       // [btnimage1 addTarget:self action:@selector(Click:)forControlEvents:UIControlEventTouchUpInside];
        
        // setting label of the first image
        
        NSString *lbname1=[divideSuperName1 objectAtIndex:i];
        UILabel *label;
        CGFloat lbWidth=width;
        CGFloat lbHeight=30;
        lbCurrentY=h1-30;
        
        label=[[UILabel alloc]initWithFrame:CGRectMake(0, lbCurrentY, lbWidth, lbHeight)];
        label.text=lbname1;
        label.textColor=[UIColor whiteColor];
        label.backgroundColor=[UIColor blackColor];
        label.alpha=0.4;
        label.textAlignment=NSTextAlignmentRight;
        [btnimage1 addSubview:label];
        [scrollView addSubview:btnimage1];
    }
    // ----------------------------------------------------------------------------
    
    
    //Create the image No. 2
    
    for(int i=0;i<[divideSuperId2 count];i++)
    {
        CGFloat lbCurrentY2=0.0f// setting the label Y axis
        
        // making image 2
     
        UIImage *image = [UIImage imageNamed:[divideSuperImage2 objectAtIndex:i]];
        UIImageView *imageView2 = [[UIImageView alloc] initWithImage:image];
        
        // frame size of image 2
        
        CGRect rect2=imageView2.frame;
        CGFloat width2=152;
        CGFloat height2=imageView2.frame.size.height/2.0;
        rect2=CGRectMake(width2+3,currentY2, width2,height2);
        imageView2.frame=rect2;
        
        currentY2+=imageView2.frame.size.height+5;
        h2=imageView2.frame.size.height;
        
        // fixing button woith image
        
        UIButton *btnImage2=[UIButton buttonWithType:UIButtonTypeCustom];
        btnImage2.frame=rect2;
        [btnImage2 setImage:imageView2.image forState:UIControlStateNormal];
        btnImage2.tag=[[divideSuperId2 objectAtIndex:i]integerValue];
        NSLog(@"%d",btnImage2.tag);
       // [btnImage2 addTarget:self action:@selector(Click:)forControlEvents:UIControlEventTouchUpInside];
        // making label 2
        
        NSString *labelName=[divideSuperName2 objectAtIndex:i];
        UILabel *label1;
        CGFloat lbwidth2=width2;
        CGFloat lbHeight=30;
        lbCurrentY2=height2-30;
        label1=[[UILabel alloc]initWithFrame:CGRectMake(0,lbCurrentY2,lbwidth2, lbHeight)];
        label1.text=labelName;
        label1.textColor=[UIColor whiteColor];
        label1.backgroundColor=[UIColor blackColor];
        label1.alpha=0.4;
        label1.textAlignment=NSTextAlignmentRight;
        [btnImage2 addSubview:label1];
        [scrollView addSubview:btnImage2];
    }
    
    
    scrollView.contentSize = CGSizeMake(151*2,currentY1+h1);
    
    
    //
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [self.view addSubview:scrollView];
    
}

-(void)searchScroll
{
        for (NSString *sTemp in arr2)
        {
            
            NSComparisonResult result = [sTemp compare:self.strSearchData options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [self.strSearchData length])];
            
            if (result == NSOrderedSame)
            {
                [resultArrayName addObject:sTemp];
            }
        }
    
    for(int i=0;i<[resultArrayName count];i++)
    {
        [resultArrayId addObject:[dict3 objectForKey:[resultArrayName objectAtIndex:i]]];
       
    }
    
    // getting image
    for(int i=0;i<[resultArrayId count];i++)
    {
        [resultArrayImage addObject:[dict2 objectForKey:[resultArrayId objectAtIndex:i]]];
       }

    NSArray *temp=[scrollView subviews];
    for(UIView *vi in temp)
    {
        [vi removeFromSuperview];
    }
    
    [self Scroll:resultArrayId name:resultArrayName image:resultArrayImage];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)txt1
{
    [txt1 resignFirstResponder];
    return YES;}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
  
    if([resultArrayId count]>0)
    {
        [resultArrayId removeAllObjects];
    }
     if([resultArrayName count]>0)
    {
        [resultArrayName removeAllObjects];
    }
    if([resultArrayImage count]>0)
    {
        [resultArrayImage removeAllObjects];
    }
    
    if([string length]==0)
    {
        NSArray *temp=[scrollView subviews];
        for(UIView *vi in temp)
        {
            [vi removeFromSuperview];
        }
        [self Scroll:arr1 name:arr2 image:arr3];
    }
        
    if([string length]>0)
    {
        self.strSearchData=[NSString stringWithFormat:@"%@%@",txt1.text,string];
        
        [self searchScroll];
    }
    else{
        NSArray *temp=[scrollView subviews];
        for(UIView *vi in temp)
        {
            [vi removeFromSuperview];
        }
    }
    

    
    return YES;
}

// method for dictionary

-(void)createDictionary

{
  //  NSDictionary *dict1;
    dict1=[NSDictionary dictionaryWithObjects:arr2 forKeys:arr1];
    
   // NSDictionary *dict2;
    dict2=[NSDictionary dictionaryWithObjects:arr3 forKeys:arr1];
    
   // NSDictionary *dict3;
    dict3=[NSDictionary dictionaryWithObjects:arr1 forKeys:arr2];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // allocating arrays
    
    arr1=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
    arr2=[[NSMutableArray alloc]initWithObjects:@"asd",@"bsd",@"csd",@"dsd",@"asgh",@"asfg",nil];
    arr3=[[NSMutableArray alloc]initWithObjects:@"img1.jpg",@"img2.jpg",@"img3.jpg",@"img4.jpg",@"img4.jpg",@"img3.jpg", nil];
    
 // here we divide the arrays so that the on load scroll view shows all the data
    
    divideSuperId2=[[NSMutableArray alloc]init];
    divideSuperId1=[[NSMutableArray alloc]init];
    
    divideSuperImage1=[[NSMutableArray alloc]init];
    divideSuperImage2=[[NSMutableArray alloc]init];
    
    divideSuperName1=[[NSMutableArray alloc]init];
    divideSuperName2=[[NSMutableArray alloc]init];

    // allocating arrays that get during search
    
    resultArrayId=[[NSMutableArray alloc]init];
    resultArrayName=[[NSMutableArray alloc]init];
    resultArrayImage=[[NSMutableArray alloc]init];
    
    // assiging delegate to text field
    
    txt1.delegate=self;
    
    // create dictionaries with array
    
    [self createDictionary];

    // scroll calling on loada
    
    [self Scroll:arr1 name:arr2 image:arr3];
    
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end