最近需要优化项目,把搜索框改了,样式如下:
明似水.png
本以为很简单,结果弄一下发现不对,特意把解决方法记录下来:
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kAdaptedWidth(254), 30)];
searchBar.barStyle = UIBarStyleDefault;
searchBar.searchBarStyle = UISearchBarStyleDefault;
searchBar.placeholder = @"搜索内容";
searchBar.delegate = self;
searchBar.showsCancelButton = NO;
searchBar.layer.cornerRadius = 30/2;
searchBar.clipsToBounds = YES;
[searchBar setImage:[UIImage imageNamed:@"djy_icon_chakan"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
searchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:searchBar.bounds.size];
[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"djy_quanyi_dise"] forState:UIControlStateNormal];
UITextField *textField = (UITextField *)[HBHuTool findViewWithClassName:@"UITextField" inView:searchBar];
textField.textColor = Color_label_DataTitle;
textField.font = FONT(12);
textField.placeholder = @"输入邀请码/名字/手机号";
注意的是叫UI切图把底色的图切了
//取消searchbar背景色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
UISearchBar适配iOS13方法:
// 替代方案 2,遍历获取指定类型的属性
+ (UIView *)findViewWithClassName:(NSString *)className inView:(UIView *)view{
Class specificView = NSClassFromString(className);
if ([view isKindOfClass:specificView]) {
return view;
}
if (view.subviews.count > 0) {
for (UIView *subView in view.subviews) {
UIView *targetView = [self findViewWithClassName:className inView:subView];
if (targetView != nil) {
return targetView;
}
}
}
return nil;
}
END.
网友评论