Customizing UISearch bar - ios

I am trying to customize my search bar like this
So far I have managed to do upto this
Now I need to know how to add image on right side, shaping the corners and changing background to an image. This is my code so far. I can do this with help of UITextField but I want to do this using the UISearchBar. Any help??
- (void)setSearchIconToFavicon
{
// commented are the things I tried out
UITextField *searchField = nil;
for (UIView *subview in searchBar.subviews)
{
if ([subview isKindOfClass:[UITextField class]])
{
searchField = (UITextField *)subview;
break;
}
}
if (searchField)
{
UIImage *image = [UIImage imageNamed: #"search_btn.png"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
//UIImage *image2 = [UIImage imageNamed: #"search_next_btn.png"];
//UIImageView *iView2 = [[UIImageView alloc] initWithImage:image2];
searchField.leftView = iView;
//searchField.rightView=iView2;
[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
searchField.textColor = [UIColor grayColor];
}
}

You can replace the Bookmark image instead, and adjust its offset if necessary.Like this..
[self.searchDisplayController.searchBar setImage:[UIImage imageNamed:#"yourImage"] forSearchBarIcon:UISearchBarIconBookmark state:UIControlStateNormal];
[self.searchDisplayController.searchBar setPositionAdjustment:UIOffsetMake(0, 0) forSearchBarIcon:UISearchBarIconBookmark];
And you can handle the button event in the delegate method:
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar
i Hope you got my point.

You can this line of code if your target application is >=5.0 to change background image of search bar.
[[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:#"searchbar.png"]forState:UIControlStateNormal];

Related

How to Add a button into iCarousel View?

I am using iCarousel for showing an image. But I want to add a button into iCarousel. I implemented it but problem is that custom button action does not work, only didSelectItem work when I click on the button. here is my code. Please, any one helps me out.
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
NSString *str=[[appController
sharedappController].allLibraryImagesArrM objectAtIndex:index];
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200.0f, 200.0f)];
((UIImageView *)view).image = [[appController sharedappController].allLibraryImagesArrM objectAtIndex:index];
view.contentMode = UIViewContentModeScaleAspectFit;
//[view addSubview:cross];
UIButton *cross = [[UIButton alloc]init];
cross.frame = CGRectMake(view.frame.size.width/2+30, view.frame.origin.y+30, 40, 40);
[cross setBackgroundImage:[UIImage imageNamed:#"circle"] forState:UIControlStateNormal];
[cross addTarget:self action:#selector(crossMethod) forControlEvents:UIControlEventTouchUpInside];
UIImage *buttonImage = [UIImage imageNamed:#"cross.png"];
[cross setBackgroundImage:buttonImage forState:UIControlStateNormal];
[view addSubview:cross];
return view;
}
Did you enable UserInteraction?
Enable UserInteraction
[view setUserInteractionEnabled:YES];

Changing UISearchBar search field background

I have a UISearchBar contained within a UIView and the UIView has been assigned to a UITableView's tableHeaderView. I'm trying to style the UISearchBar to look like this:
Out of the gate, this is what it looks like:
There are loads of SO questions and answers on how to style UISearchBar, its search field, etc., some with particular attention to backgrounds. Many of them involve traversing the UISearchBar's subviews, finding a UISearchBarBackground (or _UISearchBarSearchFieldBackgroundView) object, and setting its background color directly. I'm trying to find a supported API for doing this, however...
The setSearchFieldBackgroundImage:forState: method seems to have great potential, but this is what I get when I use a 1px white (or transparent) image using UIControlStateNormal:
Any ideas as to how to get this to work? I'd appreciate someone pointing me to a SO post that answers this, but I really do think I've read them all. Thanks a ton.
you can use the appearanceWhenContainedIn to target elements without traversing the view hierarchy. Something like:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor lightGrayColor]];
UPDATE:
As appearanceWhenContainedIn is now deprecated, use
[[UITextField appearanceWhenContainedInInstancesOfClasses:#[[UISearchBar self]]] <your setter here>];
I think the problem here is that when you use setSearchFieldBackgroundImage:forState:, the height of your image actually determines the height of the search field. The standard search field (at least as of iOS 8) is 28 points tall, so an image that height should give the effect you're after.
(Somewhat confusingly, this also means that a nine-part stretchable image generally won't look right—so if you were going for a look that wasn't just white on white, you need to use a three-part stretchable image that only stretches horizontally.)
Above iOS 5.0
[[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:#"YourBackground.png"]forState:UIControlStateNormal];
Please try following code
[[UISearchBar appearance]setBackgroundImage:[UIImage imageNamed:#“searchbar_bg.png"]];
for (UIView *searchbuttons in searchBar.subviews) {
if ([searchbuttons isKindOfClass:[UIButton class]]) {
UIButton *cancelbutton = (UIButton *)searchbuttons;
[cancelbutton setBackgroundImage:[UIImage imageNamed:#“canelBtn.png"] forState:UIControlStateNormal];
}
}
UITextField *searchField = [searchBar valueForKey:#"_searchField"];
searchField.background = [UIImage imageNamed:#"bg.png"];
You can use either the barTintColor or the backgroundImage property of the UISearchBar to directly accomplish what you are trying to do.
I reproduced your problem, and it seems to be solved by:
self.searchDisplayController.searchBar.barTintColor = [UIColor whiteColor];
or
self.searchDisplayController.searchBar.backgroundImage = [self imageWithColor:[UIColor whiteColor]];
P.S. If you are using the backgroundImage solution, you'll need to make the method imageWithColor as follows
- (UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Tell me if it works!
iO9 Perfect works.
- (void)viewDidLoad
{
[super viewDidLoad];
[[self searchSubviewsForTextFieldIn:self.searchBar] setBackgroundColor: [UIColor redColor]];
}
- (UITextField*)searchSubviewsForTextFieldIn:(UIView*)view
{
if ([view isKindOfClass:[UITextField class]]) {
return (UITextField*)view;
}
UITextField *searchedTextField;
for (UIView *subview in view.subviews) {
searchedTextField = [self searchSubviewsForTextFieldIn:subview];
if (searchedTextField) {
break;
}
}
return searchedTextField;
}
#joneswah's answer is depricated in iOS 9.
For iOS 9 put this in your AppDelegate.m. I also added workaround for keyboard opening lag, when keyboard is initiated for the first time.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Remove lag on oppening the keyboard for the first time when clicked on any UITextField
UITextField *lagFreeField = [[UITextField alloc] init];
[self.window addSubview:lagFreeField];
[lagFreeField becomeFirstResponder];
[lagFreeField resignFirstResponder];
[lagFreeField removeFromSuperview];
//searchBar background color change
[[UITextField appearanceWhenContainedInInstancesOfClasses:#[[UISearchBar class]]] setBackgroundColor:[UIColor greenColor]];//background color
[[UITextField appearanceWhenContainedInInstancesOfClasses:#[[UISearchBar class]]] setTextColor:[UIColor blackColor];//text color
return YES;
}
As others suggested, you need to traverse through your searchbar's subviews and finding the UITextField instance. BUT, you need to set its layer.backgroundColor, as setting the backgroundColor property has no effect. I'll give an example:
for view in searchBar.subviews {
for subview in view.subviews {
if let searchField = subview as? UITextField {
searchField.layer.backgroundColor = UIColor.whiteColor().CGColor
}
}
}
This will give you what you need.
My answer stably works on ios 5 and above, including this 10. Without hacks and KVO, by Apple Way
The following code will achieve the result.
_sbAddress.barTintColor = [UIColor whiteColor];
for (UIView *subView in _sbAddress.subviews) {
for(id field in subView.subviews){
if ([field isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)field;
[textField setPlaceholder:#"Search"];
}
}
}
OR
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setPlaceholder:#"Search"];

How to fix offset keyboard when UISearchbar is touched

The problem I'm having is that when a user touches into the search bar the keyboard appears fine. Then when the presentQR method (see below) is called and then dismissed and then the searchbar is touched the keyboard appears as shown in the screenshot where it is offset. This is iOS7; not sure if that matters though.
I'm adding a UISearchbar using the following code:
// search bar
UIView *searchBarView = [[UIView alloc] initWithFrame:CGRectMake(90.0, 0.0, 200.0, 44.0)];
searchBarView.autoresizingMask = 0;
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 190, 40)];
searchBar.backgroundImage = [[UIImage alloc] init];
searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.navigationItem.titleView = searchBar;
searchBar.delegate = self;
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,[UIColor whiteColor],UITextAttributeTextShadowColor,[NSValue valueWithUIOffset:UIOffsetMake(0, -1)],UITextAttributeTextShadowOffset, nil] forState:UIControlStateNormal];
UITextField *textfield = [[UITextField alloc] init];
searchBar.placeholder = #"City Search";
// hide magnifying glass
textfield = nil;
for (UIView* subView in searchBar.subviews) {
if ([subView isKindOfClass:[UITextField class]]) {
textfield = (UITextField*)subView;
[(UITextField*)subView setTextColor:[UIColor whiteColor]];
[(UITextField*)subView setFont:[UIFont fontWithName:#"DIN-Regular" size:18]];
textfield.leftViewMode = UITextFieldViewModeNever;
textfield.rightViewMode = UITextFieldViewModeAlways;
break;
}
}
UIButton *cancelButton;
for (id button in searchBar.subviews)
{
if ([button isKindOfClass:[UIButton class]])
{
cancelButton=(UIButton*)button;
break;
}
}
[searchBar addSubview:textfield];
[searchBarView addSubview:searchBar];
self.navigationItem.titleView = searchBarView;
-(void)presentQR {
QRReaderViewController *qr = [[QRReaderViewController alloc]initWithNibName:#"QRReaderViewController" bundle:nil];
UIButton *removeQRBtn=[UIButton buttonWithType:UIButtonTypeCustom];
removeQRBtn.frame=CGRectMake(260, 10, 60, 40);
[removeQRBtn addTarget:self action:#selector(removeQR) forControlEvents:UIControlEventTouchDown];
[removeQRBtn setImage:[UIImage imageNamed:#"qrcode.png"] forState:0];
[qr.view addSubview:removeQRBtn];
qr.view.backgroundColor = customColorGrey;
qr.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;
// [self presentModalViewController:qr animated:YES];
[self presentViewController:qr animated:YES completion:nil];
}
-(void)removeQR {
// [self dismissModalViewControllerAnimated:YES];
[self dismissViewControllerAnimated:YES completion:nil];
}
1st Make sure that in QRReaderViewController there is nothing like reframing window or such. There might be an element conflicting with UIWindow preventing keyboard to be shown correctly. (e.g unbalanced orientation changes.)
2nd If you didn't find anything there you could try accessing the keyboard view using the following code and attempt to reset the frame. You could put this code in keyboardWillShow method (need to register for the notification)
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWindow_Class/UIWindowClassReference/UIWindowClassReference.html#//apple_ref/c/data/UIKeyboardWillShowNotification
PS. I would suggest to just log the keyboard frame so you know when it's changed.
Reframing Keyboard: Found here: https://stackoverflow.com/a/10957843/1017340
//The UIWindow that contains the keyboard view - It some situations it will be better to actually
//You need to iterate through each window to figure out where the keyboard is, but In my applications case
//I know that the second window has the keyboard so I just reference it directly
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
//Because we cant get access to the UIPeripheral throughout the SDK we will just use UIView.
//UIPeripheral is a subclass of UIView anyways
UIView* keyboard;
//Iterate though each view inside of the selected Window
for(int i = 0; i < [tempWindow.subviews count]; i++)
{
//Get a reference of the current view
keyboard = [tempWindow.subviews objectAtIndex:i];
//Assuming this is for 4.0+, In 3.0 you would use "<UIKeyboard"
if([[keyboard description] hasPrefix:#"<UIPeripheral"] == YES)
{
NSLog(#"Keyboard Frame: %#",NSStringFromCGRect(keyboard.frame));
//HERE : try reframing the keyboard
//[keyboard setFrame:CGRectMake(...)]; /*NOT TESTED NOT RECOMMENDED*/
}
}

I am trying to set background image to UISearchBar but background image is not getting displaying in my iPhone application

In my iPhone app I am trying to set background image to UISearch Bar, my image is not getting displayed.
Here is my code
UISearchBar * tempSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake( 0, 0, self.view.bounds.size.width, 40 )];
self.searchBar = tempSearchBar;
tempSearchBar.delegate = self;
self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
self.searchBar.barStyle = UIBarStyleBlack;
self.searchBar.backgroundColor=[UIColor clearColor];
self.searchBar.backgroundImage=[UIImage imageNamed:#"Searchbox.png"];
self.searchBar.placeholder = #"Search My Data";
[self.searchBar sizeToFit];
[self.view addSubview:self.searchBar];
[tempSearchBar release];
[self.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:#"Searchbox.png"] forState:UIControlStateNormal];
By using above method I can set bg Image for searchBar
[self.searchDisplayController.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:#"search_bar"] forState:UIControlStateNormal];
While Interface Builder provides the equivalent functionality of the following code (not the desired effect though)
[self.searchDisplayController.searchBar setBackgroundImage:[UIImage imageNamed:#"search_bar"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
(void) clearSearchBarBg
{
for (UIView *subview in searchBarCity.subviews) {
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground")])
{
[subview removeFromSuperview];
break;
}
}
for (UIView *subview in searchBarCity.subviews)
{
if ([subview conformsToProtocol:#protocol(UITextInputTraits)])
{
[(UITextField *)subview setClearButtonMode:UITextFieldViewModeNever];
}
}
for(UIView *subView in searchBarCity.subviews)
{
if([subView isKindOfClass: [UITextField class]])
{
[(UITextField *)subView setKeyboardAppearance: UIKeyboardAppearanceAlert];
}
}
UITextField *searchField = [searchBarCity valueForKey:#"_searchField"];
[searchField setBackground:[UIImage imageNamed:#"SearchInputBox.png"]];// = [UIColor clearColor];
searchField.borderStyle = UITextBorderStyleNone;
[searchField setTextColor:[UIColor blackColor]];
UIImageView* image =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
image.image = [UIImage imageNamed:#"navigationBarColorCode.png"];
image.userInteractionEnabled = FALSE;
[searchBarCity insertSubview:image belowSubview:searchField];
searchBarCity.userInteractionEnabled = YES;
searchBarCity.placeholder = #"Search";
}
Use below code
[self.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:#"search_box.png"] forState:UIControlStateNormal];
self.searchDisplayController.searchBar.barTintColor = [UIColor clearColor];
self.searchBar.tintColor=[UIColor orangeColor];
Set the background image of the SearchBar:
[self.searchController.searchBar setBackgroundImage:[UIImage new] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
then change SearchField Background Image:
[self.searchController.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:#"Searchbox.png"] forState:UIControlStateNormal];
If you don't want to show the Search Icon in the search bar then do the following:
UITextField *searchField = (UITextField *)[self.searchController.searchBar valueForKey:#"searchField"];
searchField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LEFT_VIEW_WIDTH, searchField.frame.size.height)];

How to change clear button image (x button) or atleast the color of the clear button image in UISearchbar?

I need a fully transparent searchbar with cancel button. I have tried many solutions But I couldnt find a better solution yet. When I try to remove background color it shows scope bar. Can any one give me some source code for fully transperant Searchbar with can button.
Here's
addSearchbar.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.5];
UITextField *sbTextField = (UITextField *)[self.addSearchbar.subviews lastObject];
for (UIView *subview in addSearchbar.subviews)
{
NSLog(#"%#",subview);
if ([subview isKindOfClass:[UITextField class]])
{
sbTextField = (UITextField *)subview;
UIImage *image = [UIImage imageNamed: #"06_magnifying_glass.png"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
iView.frame = CGRectMake(0, 0, 24, 24);
sbTextField.leftView.frame = CGRectMake(0, 0, 24, 24);
sbTextField.leftView = iView;
[sbTextField.rightView removeFromSuperview];
CGFloat myWidth = 24.0f;
CGFloat myHeight = 24.0f;
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, myWidth, myHeight)];
[myButton setImage:[UIImage imageNamed:#"clear.png"] forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:#"clear.png"] forState:UIControlStateHighlighted];
[myButton addTarget:self action:#selector(doClear:) forControlEvents:UIControlEventTouchUpInside];
sbTextField.rightView = myButton;
sbTextField.rightViewMode = UITextFieldViewModeWhileEditing;
break;
}
if([subview isMemberOfClass:[UISegmentedControl class]])
{
UISegmentedControl *scopeBar=(UISegmentedControl *) subview;
scopeBar.tintColor = [UIColor clearColor];
}
}
[sbTextField removeFromSuperview];
[addSearchbar addSubview:sbTextField];
[addSearchbar setSearchFieldBackgroundImage:[UIImage imageNamed:#"SearchBar.png"] forState:UIControlStateNormal];
CGRect sbFrame = self.addSearchbar.frame;
// Set the default height of a textfield
sbFrame.size.height = 31;
/* 8 is the top padding for textfield inside searchbar
* You may need to add a variable to 8 according to your requirement.
*/
sbFrame.origin.y = 6+self.addSearchbar.frame.origin.y;
sbTextField.frame = sbFrame;
sbTextField.textColor = [UIColor lightGrayColor];
[sbTextField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
Need a fully transparent searchbar with cancel button and clear button but without scopebar.
Thanks in advance
As of iOS 5.0 you can do the following:
UIImage *imgClear = [UIImage imageNamed:#"clear"];
[addSearchBar setImage:imgClear forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
Thats it. You might also want to repeat the line for the UIControlStateHighlighted state.
The last thing you should be doing is digging around inside the subviews of the search bar. It is guaranteed to break some day. Use the proper API to customize any control.
See that you set the UIControlHighlighted state image first and then the UIControlStateNormal state image or else you might face an issue wherein the clearIcon is not set in the highlighted state. (Not sure why this problem occurs.)
[_searchBar setImage:[UIImage imageNamed:#"ClearIcon"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
[_searchBar setImage:[UIImage imageNamed:#"ClearIcon"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
For those of you trying this in Swift (I know someone is going to come here looking for this...) here you go:
self.searchBar.setImage(UIImage(named: "ico-cancel"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal)
self.searchBar.setImage(UIImage(named: "ico-cancel"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Highlighted)
Make sure you have the correct image in your Assets.xcassets folder.
Here’s how you change the magnifying glass and clear button icon in a UISearchBar’s UITextField
Without New Icons:
// Reference search display controller search bar's text field (in my case).
UITextField *searchBarTextField = [self.searchDisplayController.searchBar valueForKey:#"_searchField"];
// Magnifying glass icon.
UIImageView *leftImageView = (UIImageView *)searchBarTextField.leftView;
leftImageView.image = [LeftImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
leftImageView.tintColor = [UIColor whiteColor];
// Clear button
UIButton *clearButton = [searchBarTextField valueForKey:#"_clearButton"];
[clearButton setImage:[clearButton.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
clearButton.tintColor = [UIColor whiteColor];

Resources