我正在搜索将UILabel添加到搜索字段前面的UISearchBar的方法。
我试图像这样添加一个UILabel:
- (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];
}
结果看起来像==> http://i.stack.imgur.com/x3sel.png
我怎样才能完成这项工作? 它应该是
[356] [搜索字段] [取消]
感谢您的任何建议
答案 0 :(得分:1)
您可以调整搜索文本位置。只需添加:
self.searchDisplayController.searchBar.searchTextPositionAdjustment = UIOffsetMake(65., 0.);
答案 1 :(得分:0)
我确实解决了它。子类UISearchBar并在layoutSubviews中进行更改。
这是我的代码。
#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
干杯