Как изменить цвет внутреннего фона компонента UISearchBar на iOS
Я знаю как удалить/изменить UISearchBar цвет фона вокруг поля поиска:
[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
self.searchBar.backgroundColor = [UIColor grayColor];

но не знаю как это сделать внутри это так:

Это должно быть совместимо с iOS 4.3+.
18 ответов:
используйте этот код, чтобы изменить строку поиска в
UITextFieldbackgroundImage:UITextField *searchField; NSUInteger numViews = [searchBar.subviews count]; for (int i = 0; i < numViews; i++) { if ([[searchBar.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform? searchField = [searchBar.subviews objectAtIndex:i]; } } if (searchField) { searchField.textColor = [UIColor whiteColor]; [searchField setBackground: [UIImage imageNamed:@"yourImage"]]; //set your gray background image here [searchField setBorderStyle:UITextBorderStyleNone]; }использовать ниже код, чтобы изменить
UISearchBarIcon:UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourSearchBarIconImage"]]; searchIcon.frame = CGRectMake(10, 10, 24, 24); [searchBar addSubview:searchIcon]; [searchIcon release];кроме того, чтобы изменить значок панели поиска, вы можете использовать следующий встроенный метод на
UISearchBar(который доступен от iOS 5+):- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)stateздесь вы можете установить 4 типа
UISearchBarIconт. е.:
UISearchBarIconBookmarkUISearchBarIconClearUISearchBarIconResultsListUISearchBarIconSearchЯ надеюсь, что это поможет вам...
просто настроить само текстовое поле.
Я просто делаю это, и это отлично работает для меня (iOS 7).
UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"]; txfSearchField.backgroundColor = [UIColor redColor];таким образом, вам не нужно создавать образ, размер и т. д...
решение, которое не включает в себя какой-либо частный API ! :)
В настоящее время ( вероятно, начиная с iOS 5 ) вы можете сделать это, просто для одного цвета случаев, таким образом:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor redColor]];но, пожалуйста, имейте в виду, что, поскольку он основан на внешнем виде, изменение будет глобальным для приложения (это может быть преимуществом или недостатком решения).
для Swift вы можете использовать (он будет работать для iOS 9 и выше):
if #available(iOS 9.0, *) { UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrayColor() }вы не нужно
#availableЕсли ваш проект поддерживает iOS 9 и новее.Если вам нужно поддерживать более ранние версии iOS и хотите использовать Swift, посмотрите на этой вопрос.
Swift 3, xcode 8.2.1
полная выборка
расширение UISearchBar
extension UISearchBar { private func getViewElement<T>(type: T.Type) -> T? { let svs = subviews.flatMap { .subviews } guard let element = (svs.filter { is T }).first as? T else { return nil } return element } func setTextFieldColor(color: UIColor) { if let textField = getViewElement(type: UITextField.self) { switch searchBarStyle { case .minimal: textField.layer.backgroundColor = color.cgColor textField.layer.cornerRadius = 6 case .prominent, .default: textField.backgroundColor = color } } } }использование
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 20, width: UIScreen.main.bounds.width, height: 44)) //searchBar.searchBarStyle = .prominent view.addSubview(searchBar) searchBar.placeholder = "placeholder" searchBar.setTextFieldColor(color: UIColor.green.withAlphaComponent(0.3))результат 1
searchBar.searchBarStyle = .prominent // or defaultрезультат 2
searchBar.searchBarStyle = .minimal
по словам UISearchBar документации:
вы должны использовать эту функцию для iOS 5.0+.
- (void)setSearchFieldBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)stateпример использования:
[mySearchBar setSearchFieldBackgroundImage:myImage forState:UIControlStateNormal];к сожалению, в iOS 4 вам нужно вернуться к менее сложным методам. См. другие ответы.
Как Accatyyc говорит для iOS5 + используйте setSearchFieldBackgroundImage, но вам либо нужно создать графику, либо сделать следующее:
CGSize size = CGSizeMake(30, 30); // create context with transparent background UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); // Add a clip before drawing anything, in the shape of an rounded rect [[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0,0,30,30) cornerRadius:5.0] addClip]; [[UIColor grayColor] setFill]; UIRectFill(CGRectMake(0, 0, size.width, size.height)); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [self.searchBar setSearchFieldBackgroundImage:image forState:UIControlStateNormal];
как насчет apple way?
UISearchBar.appearance().setSearchFieldBackgroundImage(myImage, for: .normal)вы можете установить любое изображение на ваш дизайн!
но если вы хотите создать все programmaticle, вы можете сделать это
мое решение о Swift 3
let searchFieldBackgroundImage = UIImage(color: .searchBarBackground, size: CGSize(width: 44, height: 30))?.withRoundCorners(4) UISearchBar.appearance().setSearchFieldBackgroundImage(searchFieldBackgroundImage, for: .normal)где я использую расширение помощников
public extension UIImage { public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } public func withRoundCorners(_ cornerRadius: CGFloat) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, scale) let rect = CGRect(origin: CGPoint.zero, size: size) let context = UIGraphicsGetCurrentContext() let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius) context?.beginPath() context?.addPath(path.cgPath) context?.closePath() context?.clip() draw(at: CGPoint.zero) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return image; } }
Я нашел, что это лучший способ настроить внешний вид различных атрибутов панели поиска в Swift 2.2 и iOS 8 + с помощью
UISearchBarStyle.MinimalsearchBar = UISearchBar(frame: CGRectZero) searchBar.tintColor = UIColor.whiteColor() // color of bar button items searchBar.barTintColor = UIColor.fadedBlueColor() // color of text field background searchBar.backgroundColor = UIColor.clearColor() // color of box surrounding text field searchBar.searchBarStyle = UISearchBarStyle.Minimal // Edit search field properties if let searchField = searchBar.valueForKey("_searchField") as? UITextField { if searchField.respondsToSelector(Selector("setAttributedPlaceholder:")) { let placeholder = "Search" let attributedString = NSMutableAttributedString(string: placeholder) let range = NSRange(location: 0, length: placeholder.characters.count) let color = UIColor(white: 1.0, alpha: 0.7) attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range) attributedString.addAttribute(NSFontAttributeName, value: UIFont(name: "AvenirNext-Medium", size: 15)!, range: range) searchField.attributedPlaceholder = attributedString searchField.clearButtonMode = UITextFieldViewMode.WhileEditing searchField.textColor = .whiteColor() } } // Set Search Icon let searchIcon = UIImage(named: "search-bar-icon") searchBar.setImage(searchIcon, forSearchBarIcon: .Search, state: .Normal) // Set Clear Icon let clearIcon = UIImage(named: "clear-icon") searchBar.setImage(clearIcon, forSearchBarIcon: .Clear, state: .Normal) // Add to nav bar searchBar.sizeToFit() navigationItem.titleView = searchBar
без использования частных API:
for (UIView* subview in [[self.searchBar.subviews lastObject] subviews]) { if ([subview isKindOfClass:[UITextField class]]) { UITextField *textField = (UITextField*)subview; [textField setBackgroundColor:[UIColor redColor]]; } }
лучшее решение-установить внешний вид
UITextFieldвнутриUISearchBar[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];
просто пересечь все представления с помощью метода категории (проверено в iOS 7 и не использует частный API):
@implementation UISearchBar (MyAdditions) - (void)changeDefaultBackgroundColor:(UIColor *)color { for (UIView *subview in self.subviews) { for (UIView *subSubview in subview.subviews) { if ([subSubview isKindOfClass:[UITextField class]]) { UITextField *searchField = (UITextField *)subSubview; searchField.backgroundColor = color; break; } } } } @endпоэтому после импорта категории в свой класс, просто используйте его как:
[self.searchBar changeDefaultBackgroundColor:[UIColor grayColor]];имейте в виду, если вы поставите этот тут после
[[UISearchBar alloc] init]line, он еще не будет работать, так как подвиды строки поиска все еще создаются. Поместите его на несколько строк вниз после настройки остальной части строки поиска.
Для Изменения Только Цвета :
searchBar.tintColor = [UIColor redColor];Для Применения Фонового Изображения:
[self.searchBar setSearchFieldBackgroundImage: [UIImage imageNamed:@"Searchbox.png"] forState:UIControlStateNormal];
- (void)viewDidLoad { [super viewDidLoad]; [[self searchSubviewsForTextFieldIn:self.searchBar] setBackgroundColor:[UIColor redColor]]; } - (UITextField*)searchSubviewsForTextFieldIn:(UIView*)view { if ([view isKindOfClass:[UITextField class]]) { return (UITextField*)view; } UITextField *searchedTextField; for (UIView *subview in view.subviews) { searchedTextField = [self searchSubviewsForTextFieldIn:subview]; if (searchedTextField) { break; } } return searchedTextField; }
Это версия Swift (swift 2.1 / IOS 9)
for view in searchBar.subviews { for subview in view.subviews { if subview .isKindOfClass(UITextField) { let textField: UITextField = subview as! UITextField textField.backgroundColor = UIColor.lightGrayColor() } } }
для iOS 9 Используйте это:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // Remove lag on oppening the keyboard for the first time UITextField *lagFreeField = [[UITextField alloc] init]; [self.window addSubview:lagFreeField]; [lagFreeField becomeFirstResponder]; [lagFreeField resignFirstResponder]; [lagFreeField removeFromSuperview]; //searchBar background color change [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setBackgroundColor:[UIColor greenColor]]; [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTextColor:[UIColor blackColor]; return YES; }
Swift 3
for subview in searchBar.subviews { for innerSubview in subview.subviews { if innerSubview is UITextField { innerSubview.backgroundColor = UIColor.YOUR_COLOR_HERE } } }
для Swift 3+, Используйте это:
for subView in searchController.searchBar.subviews { for subViewOne in subView.subviews { if let textField = subViewOne as? UITextField { subViewOne.backgroundColor = UIColor.red //use the code below if you want to change the color of placeholder let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel textFieldInsideUISearchBarLabel?.textColor = UIColor.blue } } }
@Евгений Ильин решение Евгения Ильина является лучшим. Я написал С версия основывается на этом решении.
создать , и рекламировать два метода класса в UIImage+YourCategory.h
+ (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect; + (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius;реализовать методы в UIImage+YourCategory.м
// create image with your color + (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect { UIGraphicsBeginImageContext(imageRect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, imageRect); UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } // get a rounded-corner image from UIImage instance with your radius + (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius { CGRect rect = CGRectMake(0.0, 0.0, 0.0, 0.0); rect.size = image.size; UIGraphicsBeginImageContextWithOptions(image.size, NO, [UIScreen mainScreen].scale); UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius]; [path addClip]; [image drawInRect:rect]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; }сделать свой собственный
UISearchBarв своемViewControllerCGRect rect = CGRectMake(0.0, 0.0, 44.0, 30.0); UIImage *colorImage = [UIImage imageWithColor:[UIColor yourColor] withSize:rect]; UIImage *finalImage = [UIImage roundImage:colorImage withRadius:4.0]; [yourSearchBar setSearchFieldBackgroundImage:finalImage forState:UIControlStateNormal];



Comments