UISearchBar是在iOS开发中经常用到的一个组件,那么我们如何来实现一个类似AMAP中的SearchBar呢?
我们可以首先来观察一下,这个searchBar和默认的有什么区别?
默认的SearchBar,如下图:
首先有起点和终点这样的文字提示,默认的是一个搜索图标。
其次是文本框的边框是圆角矩形,默认的是圆角为半圆型。
那么我们实现自定义的UISearchBar就需要修改这两项。
实现的方式就是重新实现UISearchBar的layoutSubviews方法
- (void)layoutSubviews {
UITextField *searchField;
NSUInteger numViews = [self.subviews count];
for(int i = 0; i < numViews; i++) {
if([[self.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform?
searchField = [self.subviews objectAtIndex:i];
}
}
if(!(searchField == nil)) {
searchField.textColor = [UIColor redColor];
// [searchField setBackground: [UIImage imageNamed:@"esri.png"] ];
[searchField setBorderStyle:UITextBorderStyleRoundedRect];
UIImage *image = [UIImage imageNamed: @"esri.png"];
UIImageView *iView = [[UIImageView alloc] initWithImage:image];
searchField.leftView = iView;
[iView release];
}
[super layoutSubviews];
}
最终效果如下: