I'm searching for a way to add a UILabel to an UISearchBar in Front of the Searchfield.
I tried to add a UILabel like that:
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
self.searchDisplayController.searchBar.showsCancelButton = YES;
UILabel *searchResultCount = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, 50, 28)];
searchResultCount.text = @"357"; //Itemscount of Searchresult
[self.searchDisplayController.searchBar addSubview:searchResultCount];
}
The Result looks like that ==> https://i.sstatic.net/x3sel.png
How can i get this work ? It should be
[356] [Searchfield] [Cancel]
Thanks for any advise
I did solved it. Subclass UISearchBar and make changes in layoutSubviews.
Here is my Code.
#import "CustomSearchBar.h"
@implementation CustomSearchBar
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void)layoutSubviews
{
[super layoutSubviews];
float cancelButtonWidth = 84.0;
UITextField *searchField;
UILabel *resultLabel;
UIView *topView = [self.subviews lastObject];
for (UIView *subView in topView.subviews)
{
if ([subView isKindOfClass:NSClassFromString(@"UITextField")])
{
searchField = (UITextField *)subView;
}
else if ([subView isKindOfClass:NSClassFromString(@"UILabel")])
{
resultLabel = (UILabel*)subView;
}
}
if(!searchField) {return; }
if (self.showsCancelButton)
{
if(!resultLabel)
{
resultLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, 40, 28)];
resultLabel.text = @"356";
[topView addSubview:resultLabel];
}
[searchField setFrame:CGRectMake(60, 8, self.frame.size.width - 100 - cancelButtonWidth, 28)];
}
else
{
[searchField setFrame:CGRectMake(8, 8, 484, 28)];
if(resultLabel)
{
[resultLabel removeFromSuperview];
}
}
}
@end
Cheers