Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make UItextfield to function like UISearchBar

I want to change the looks of UISearchBar: So,

If there's a way by which I can make my UITextField(in a custom background for search) to function like UISearchBar ? or subclassing and overriding the - (void)layoutSubviews is the only way ?

Kindly tell How to subclass it !!!

like image 931
nr5 Avatar asked Jan 03 '13 07:01

nr5


2 Answers

you can change the UISearchBar background using this bellow code..

for (UIView *subview in searchBar.subviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
            UIView *bg = [[UIView alloc] initWithFrame:subview.frame];
            bg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"SkyBackground.jpeg"]];
            [searchBar insertSubview:bg aboveSubview:subview];
            [subview removeFromSuperview];
            break;
        }
    }

From this code you can set image or anything else for background of UISearchBar.

Also see my this answer with some other functionality to change the searchbar component layout..How to change inside background color of UISearchBar component on iOS

UPDATE:

for change the Cancel button appearance use this bellow code...

   UIButton *cancelButton = nil;

    for(UIView *subView in searchBar.subviews)
    {
        if([subView isKindOfClass:[UIButton class]])
        {
            cancelButton = (UIButton*)subView;
            //do something here with this cancel Button
        }
    }
like image 78
Paras Joshi Avatar answered Oct 05 '22 09:10

Paras Joshi


Its also possible using UITextFieldDelegates

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{    
NSString *searchString;
if (string.length > 0) {        
    searchString = [NSString stringWithFormat:@"%@%@",textField.text, string];
} else {
   searchString = [textField.text substringToIndex:[textField.text length] - 1];
}
NSPredicate *filter = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchString];
resultArray = [[resultTempArray filteredArrayUsingPredicate:filter] mutableCopy];

if (!searchString || searchString.length == 0) {

    resultArray = [resultTempArray mutableCopy];
} else {
    if (resultArray.count == 0) {
NSLog(@"No data From Search");
    }
}    
[tableView reloadData];    
return YES;
}
like image 26
Sreekanth Avatar answered Oct 05 '22 10:10

Sreekanth