System UISearchBar
:
Demand:
Two scenarios:
- Locate
UISearchBar
the magnifying glass icon and modify the frame. At the same time, determine the color of the placeholder if there are no text content changes.
- Using
UISearchBar
the text value, the magnifying glass automatically left the character, let UISearchBar
set a default text, after clicking Uisearchbar Start Editing, if there is no value, set Text
to the @ "", and also to modify placeholderLabel
the color according to the state. Too cumbersome, not recommended!)
Implementation code:
@interfaceViewcontroller () <UISearchBarDelegate>/** Xib Search box*/@property (Weak, nonatomic) Iboutlet Uisearchbar*Searchbar;/** Search for pictures (magnifier)*/@property (nonatomic, weak) Uiimageview*IMGV;@end@implementationViewcontroller- (void) Viewdidappear: (BOOL) animated{[Super viewdidappear:animated]; //find a magnifying glass picture ImageView for(Uiimageview *IMGVinch_searchbar.subviews.firstobject.subviews.lastobject.subviews) { if([IMGV Ismemberofclass:[uiimageviewclass]]) {Imgv.frame= CGRectMake (8,7.5, -, -); _IMGV=IMGV; [_IMGV addobserver:self Forkeypath:@"Frame"Options:nskeyvalueobservingoptionnew Context:nil]; } } //set Searchbar text color[self updateseachbar];}- (void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID)ObjectChange: (Nsdictionary<nskeyvaluechangekey,ID> *) Change context: (void*) context{//Remove the viewer before modifying the Magnifier frame[_IMGV removeobserver:self Forkeypath:@"Frame"]; //Modify Frame_imgv.frame = CGRectMake (8,7.5, -, -); //Add Observer again[_IMGV addobserver:self Forkeypath:@"Frame"options:nskeyvalueobservingoptionnew Context:nil];}#pragmaMark-uisearchbardelegate Proxy Method-(void) Searchbartextdidbeginediting: (Uisearchbar *) searchbar{if([Searchbar.text IsEqualToString:searchBar.placeholder]) {//Display placeholder when no text is presentSearchbar.text =@""; } //get to Uisearchbar in UitextfieldUitextfield *searchfield = [Searchbar valueforkey:@"_searchfield"]; //start editing to modify the TextColor colorSearchfield.textcolor =[Uicolor Blackcolor]; Searchfield.clearbuttonmode=uitextfieldviewmodewhileediting;}- (void) Searchbartextdidendediting: (Uisearchbar *) searchbar{[self Updateseachbar];}#pragmaMark-Sets the Searchbar color and clearbuttonmode-based on the text content (void) updateseachbar{if([_searchbar.text isequaltostring:@""]) {//when the text content is emptyUitextfield *searchfield = [_searchbar valueforkey:@"_searchfield"]; //Modify TextColor to PlaceholdercolorSearchfield.textcolor = [Searchfield valueforkeypath:@"_placeholderlabel.textcolor"]; Searchfield.text=Searchfield.placeholder; //Remove Right ClearbuttonSearchfield.clearbuttonmode =Uitextfieldviewmodenever; }}- (void) dealloc{//removing observers[_searchbar removeobserver:self Forkeypath:@"Frame"];}
iOS let Uisearchbar search icon and placeholder left display