Ich kann UISearchBar
Hintergrundfarbe um das Suchfeld entfernen/ändern:
[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
self.searchBar.backgroundColor = [UIColor grayColor];
Aber ich weiß nicht, wie man das so macht:
Dies muss mit iOS 4.3 und höher kompatibel sein.
Verwenden Sie diesen Code, um die UITextField
backgroundImage von searchBar zu ändern:
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];
}
Verwenden Sie den folgenden Code, um die UISearchBarIcon
zu ändern:
UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourSearchBarIconImage"]];
searchIcon.frame = CGRectMake(10, 10, 24, 24);
[searchBar addSubview:searchIcon];
[searchIcon release];
Um das searchBar-Symbol zu ändern, können Sie auch die folgende integrierte Methode für UISearchBar
verwenden (verfügbar unter iOS 5+ ):
- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state
Hier können Sie 4 Typen von UISearchBarIcon
d.
UISearchBarIconBookmark
UISearchBarIconClear
UISearchBarIconResultsList
UISearchBarIconSearch
Ich hoffe das hilft dir ...
Passen Sie einfach das Textfeld selbst an.
Ich mache das einfach und es funktioniert gut für mich (iOS 7).
UITextField *txfSearchField = [_searchBar valueForKey:@"_searchField"];
txfSearchField.backgroundColor = [UIColor redColor];
Auf diese Weise müssen Sie kein Bild erstellen, die Größe ändern usw.
Lösung, die keine private API beinhaltet! :)
Derzeit ( wahrscheinlich seit iOS 5 ) können Sie dies für einfache Farbfälle auf folgende Weise tun:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor redColor]];
denken Sie jedoch daran, dass die Änderung für die App global sein wird (dies kann ein Vorteil oder ein Nachteil der Lösung sein).
Für Swift können Sie verwenden (es funktioniert für iOS 9 und höher):
if #available(iOS 9.0, *) {
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrayColor()
}
Sie benötigen #available
nicht, wenn Ihr Projekt iOS 9 und neuer unterstützt.
Wenn Sie frühere Versionen von iOS unterstützen und Swift verwenden möchten, werfen Sie einen Blick auf this question.
Swift 3, xcode 8.2.1
UISearchBar-Customizing-Beispiel
UISearchBar-Erweiterung
extension UISearchBar {
private func getViewElement<T>(type: T.Type) -> T? {
let svs = subviews.flatMap { $0.subviews }
guard let element = (svs.filter { $0 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))
searchBar.searchBarStyle = .prominent // or default
searchBar.searchBarStyle = .minimal
Gemäß der UISearchBar-Dokumentation :
Sie sollten diese Funktion für iOS 5.0 und höher verwenden.
- (void)setSearchFieldBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state
Anwendungsbeispiel:
[mySearchBar setSearchFieldBackgroundImage:myImage forState:UIControlStateNormal];
Leider müssen Sie in iOS 4 auf weniger anspruchsvolle Methoden zurückgreifen. Siehe andere Antworten.
Wie Accatyyc für iOS5 + sagt, verwenden Sie setSearchFieldBackgroundImage, aber Sie müssen entweder eine Grafik erstellen oder Folgendes tun:
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];
was ist mit Apple?
UISearchBar.appearance().setSearchFieldBackgroundImage(myImage, for: .normal)
Wenn Sie jedoch alle Programmartikel erstellen möchten, können Sie dies tun
meine Lösung auf Swift 3
let searchFieldBackgroundImage = UIImage(color: .searchBarBackground, size: CGSize(width: 44, height: 30))?.withRoundCorners(4)
UISearchBar.appearance().setSearchFieldBackgroundImage(searchFieldBackgroundImage, for: .normal)
wo ich helfer erweiterung benutze
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;
}
}
Ich habe festgestellt, dass dies die beste Möglichkeit ist, das Erscheinungsbild verschiedener Suchleistenattribute in Swift 2.2 und iOS 8+ mithilfe von UISearchBarStyle.Minimal
anzupassen.
searchBar = 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
ohne private APIs zu verwenden:
for (UIView* subview in [[self.searchBar.subviews lastObject] subviews]) {
if ([subview isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField*)subview;
[textField setBackgroundColor:[UIColor redColor]];
}
}
Eine bessere Lösung besteht darin, das Aussehen der UITextField
in UISearchBar
festzulegen.
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];
Durchlaufen Sie alle Ansichten mithilfe einer Kategoriemethode (in iOS 7 überprüft und verwendet keine private 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
Nachdem Sie die Kategorie in Ihre Klasse importiert haben, verwenden Sie sie einfach wie folgt:
[self.searchBar changeDefaultBackgroundColor:[UIColor grayColor]];
Denken Sie daran, wenn Sie diese sofort nach der [[UISearchBar alloc] init]
-Zeile einfügen, funktioniert dies noch nicht, da die Unteransichten der Suchleiste noch erstellt werden. Nachdem Sie den Rest der Suchleiste eingerichtet haben, legen Sie ihn ein paar Zeilen nach unten.
Nur zum Ändern der Farbe:
searchBar.tintColor = [UIColor redColor];
Zum Anwenden des Hintergrundbildes:
[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;
}
Dies ist die Swift-Version (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()
}
}
}
Für iOS 9 verwenden Sie Folgendes:
- (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
}
}
}
Verwenden Sie für Swift 3+ Folgendes:
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
}
}
}
Das hat für mich funktioniert.
- (void)setupSearchBar
{
[self.searchBar setReturnKeyType:UIReturnKeySearch];
[self.searchBar setEnablesReturnKeyAutomatically:NO];
[self.searchBar setPlaceholder:FOLocalizedString(@"search", nil)];
[self.searchBar setBackgroundImage:[UIImage new]];
[self.searchBar setBackgroundColor:[UIColor myGreyBGColor]];
[self.searchBar setBarTintColor:[UIColor myGreyBGColor]];
[self.searchBar setTintColor:[UIColor blueColor]];
}
@EvGeniy Ilyin EvGeniy Ilyins Lösung ist die beste ... Ich habe eine Objective-C -Version geschrieben, die auf dieser Lösung basiert.
Erstellen Sie eine UIImage
-Kategorie und bewerben Sie zwei Klassenmethoden in UIImage + YourCategory.h
+ (UIImage *)imageWithColor:(UIColor *)color withSize:(CGRect)imageRect;
+ (UIImage *)roundImage:(UIImage *)image withRadius:(CGFloat)radius;
Implementiere Methoden in UIImage + YourCategory.m
// 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;
}
Erstelle deine eigene UISearchBar
in deiner ViewController
CGRect 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];
Um dies unter iOS 13+ zu tun,
searchController.searchBar.searchTextField.backgroundColor = // your color here
Beachten Sie, dass searchTextField.borderStyle
standardmäßig auf roundedRect
eingestellt ist, wodurch eine leichte graue Überlagerung auf die von Ihnen festgelegte Farbe angewendet wird. Wenn dies unerwünscht ist, tun Sie dies
searchController.searchBar.searchTextField.borderStyle = .none
Dadurch wird die graue Überlagerung entfernt, aber auch die abgerundeten Ecken.
Mit Swift 4 würde ich nur empfehlen, dass Sie keinen zusätzlichen Code benötigen:
self.searchBar.searchBarStyle = .prominent
self.searchBar.barStyle = .black
Sie können auch .prominent in .minimal ändern, wenn der äußere Hintergrund nicht grau sein soll.