iOS navigation bar Searchbar control Although it is very useful, but sometimes the style of the control can not meet our needs, such as we need to the right side of the navigation bar has a magnifying glass, the system provides the control does not have this, which requires us to customize a such searchbar.
1, because the Searchbar control input when and TextField think like, so we customize the control to inherit with TextField, from the name of Searchview
We can take a look at what's inside searchView.h.
1 #import <UIKit/UIKit.h>23@interface Searchview:uitextfield 4 5 @end
2, first of all we want to implement the initialization method inside the SEARCHVIEW.M:
1-(ID) initWithFrame: (CGRect) Frame2 {3Self =[Super Initwithframe:frame];4 if(self) {5[Self searchview];//calling the Searchview method6 }7 }8 9 #pragmaMark implements the Searchview methodTen-(void) Searchview One { ASelf.placeholder =@"search for a store or product"; - //set the style of TextField -Self.borderstyle =Uitextborderstyleroundedrect; the //set the return key style of the keyboard we change to search words -Self.returnkeytype =Uireturnkeysearch; - //Create a ImageView object -Uiimageview * Imgview =[[Uiimageview alloc]init]; + //to set user interactivity for Imgview -imgview.userinteractionenabled =YES; + //Assigning a value to Imgview tabbar_discover is a magnifying glass picture AImgview.image = [UIImage imagenamed:@"Tabbar_discover"]; at //set the Rightview property of the self (TextField) and the properties of Rightviewmode -Self.rightview =Imgview; -Self.rightviewmode =uitextfieldviewmodealways; - //Add a gesture to this picture -UITapGestureRecognizer * tap =[[UITapGestureRecognizer alloc]initwithtarget:self Action: @selector (Btnclick:)]; - [Imgview Addgesturerecognizer:tap]; in - to } + //Implement button click events --(void) Btnclick: (UIButton *) btn the { *NSLog (@"111111111111%@", self.text); $NSLog (@"5555");Panax Notoginseng}
3, in viewcontroller.m inside realize first remember import header file Yo!
1 #import "ViewController.h"2 #import "searchView.h"3 4 @interfaceViewcontroller () <UITextFieldDelegate>5 {6Searchview *Search;7 }8 @end9 Ten @implementationViewcontroller One A- (void) Viewdidload { - [Super Viewdidload]; - theSearch = [[Searchview alloc]initwithframe:cgrectmake ( -, -,280, +)]; -Search.Delegate=Self ; -Search.layer.cornerRadius = -; -Search.clipstobounds =YES; + [Self.view Addsubview:search]; - + A } at-(BOOL) Textfieldshouldreturn: (Uitextfield *) TextField - { -NSLog (@"%@", search.text); - returnYES; -}
That's it. Let's take a look at the run
Does that make the effect you want?? Hey
iOS Development custom Searchbar navigation bar right side display Magnifier