UISearchBar 自定义处理
首先通過 KVC 獲取到內(nèi)部的 textField, 然后自定制處理
UITextField *searchField = [searchBar valueForKey:@"searchField"];
if (searchField) {
[searchField setBorderStyle:UITextBorderStyleNone];
//placeHolder顏色
[searchField setValue:_placeholderColor forKeyPath:@"_placeholderLabel.textColor"];
searchField.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
searchField.textColor = _textColor;
//字體大小
[searchField setValue:_placeHolderFont forKeyPath:@"_placeholderLabel.font"];
searchField.font = _textFont;
UIImage *image = _leftImage;
UIImageView *leftImg = [[UIImageView alloc] initWithImage:image];
leftImg.frame = CGRectMake(0,0,image.size.width, image.size.height);
searchField.leftView = leftImg;
}
其他: 添加圓角(放在一個(gè)有圓角的 bgView上面)
UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(20, 220, 300, 30)];
bg.backgroundColor = [UIColor whiteColor];
[self.view addSubview:bg];
bg.layer.cornerRadius = 15;
bg.layer.masksToBounds = YES;
UISearchBar *bar = [[UISearchBar alloc]initWithFrame: bg.bounds];
[bg addSubview:bar];
bar.placeholder = @"搜索...";
[bar setBackgroundImage:[UIImage imageNamed:@"clearImage@2x"]];
修改圓角大小
首先在 UIView 的 category 里加一個(gè)方法:
- (UIView*)subViewOfClassName:(NSString*)className {
for (UIView* subView in self.subviews) {
if ([NSStringFromClass(subView.class) isEqualToString:className]) {
return subView;
} UIView* resultFound = [subView subViewOfClassName:className];
if (resultFound) {
return resultFound;
}
}
return nil;
} 用的時(shí)候:
UIView* backgroundView = [searchBar subViewOfClassName:@"_UISearchBarSearchFieldBackgroundView"];
backgroundView.layer.cornerRadius = 14.0f;
backgroundView.clipsToBounds = YES;
用這個(gè)方法還可以改取消按鈕的顏色、字體什么的。
總結(jié)
以上是生活随笔為你收集整理的UISearchBar 自定义处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 妃子笑为什么叫妃子笑?
- 下一篇: C#总结(3)