iOS 11 自定义导航栏中的搜索栏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46007260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:24:39  来源:igfitidea点击:

iOS 11 customise search bar in navigation bar

iosswiftuinavigationbaruisearchbar

提问by Darko

I want to change the color of the text and icon in the iOS 11 searchbar when it is embedded in the navigation bar. So placeholder text, search text and search icon.

我想在 iOS 11 搜索栏中嵌入导航栏中时更改文本和图标的颜色。所以占位符文本、搜索文本和搜索图标。

enter image description here

在此处输入图片说明

if #available(iOS 11.0, *) {
    navigationController?.navigationBar.prefersLargeTitles = false
    let searchController = UISearchController(searchResultsController: nil)
    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = false

    searchController.searchBar.placeholder = "Suchen"
    searchController.searchBar.tintColor = .white
}

As you can see in the image, the text is grey on a deep blue background, which looks ugly. I want to text and icon to be at least white. (changing the blue background color also does not work really good, see my other question)

正如您在图像中看到的,深蓝色背景上的文本是灰色的,看起来很难看。我希望文本和图标至少为白色。(更改蓝色背景颜色也不起作用,请参阅我的其他问题

The only thing which works is changing the color of the blinking cursor and the "cancel" button, which is done with the .tintColor property.

唯一有效的是更改闪烁光标和“取消”按钮的颜色,这是通过 .tintColor 属性完成的。

Solutions which seems to work in iOS 10 and below seem not work anymore in iOS 11, so please post only solutions which you know working in iOS 11. Thanks.

似乎适用于 iOS 10 及更低版本的解决方案在 iOS 11 中似乎不再适用,因此请仅发布您知道适用于 iOS 11 的解决方案。谢谢。

Maybe I miss the point about this "automatic styling" in iOS 11. Any help is appreciated.

也许我错过了 iOS 11 中关于这个“自动样式”的要点。感谢任何帮助。

回答by Darko

I just found out how to set also the rest of them: (with some help of Brandon, thanks!)

我刚刚找到了如何设置其余部分的方法:(在布兰登的帮助下,谢谢!)

The "Cancel" text:

“取消”文本:

searchController.searchBar.tintColor = .white

The search icon:

搜索图标:

searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.search, state: .normal)

The clear icon:

清晰的图标:

searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.clear, state: .normal)

The search text:

搜索文本:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]

Thanks for the help @Brandon!

感谢@Brandon 的帮助!

enter image description here

在此处输入图片说明

The placeholder:

占位符:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

enter image description here

在此处输入图片说明

The white background:

白色背景:

let searchController = UISearchController(searchResultsController: nil)
searchController.delegate = self

let searchBar = searchController.searchBar
searchBar.tintColor = UIColor.white
searchBar.barTintColor = UIColor.white

if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
    textfield.textColor = UIColor.blue
    if let backgroundview = textfield.subviews.first {

        // Background color
        backgroundview.backgroundColor = UIColor.white

        // Rounded corner
        backgroundview.layer.cornerRadius = 10;
        backgroundview.clipsToBounds = true;
    }
}

if let navigationbar = self.navigationController?.navigationBar {
    navigationbar.barTintColor = UIColor.blue
}

navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false

enter image description here

在此处输入图片说明

Taken from here.

取自这里

回答by Brandon

Put

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

and

UISearchBar.appearance().tintColor = UIColor.whitein the AppDelegate.

UISearchBar.appearance().tintColor = UIColor.whiteAppDelegate.

Alternatively, put them both in [UIViewController viewDidLoad:]

或者,将它们都放入 [UIViewController viewDidLoad:]

回答by Donny

Set Search Text Color

设置搜索文本颜色

(UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]) ).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

Set Search Placeholder Color

设置搜索占位符颜色

(UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]) ).attributedPlaceholder = [NSForegroundColorAttributeName: UIColor.white]

回答by ingconti

my two cents for Swift 4.x, lightly cleaned up.

我 Swift 4.x 的两美分,轻轻清理。

Add in controller or App Delegate:

添加控制器或应用程序委托:

appearance.backgroundColor = .green
let myFont = UIFont.italicSystemFont(ofSize: 12)
let attribs = [
    NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): myFont,
    NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.red
]

appearance.defaultTextAttributes =  attribs

in controller:

在控制器中:

self.searchBar.barTintColor = .blue

You will get Blue background, green search bar background, red italic font:

您将获得蓝色背景、绿色搜索栏背景、红色斜体字体:

enter image description here

在此处输入图片说明

回答by Gal Danay

I tried Daroko solution, but i had a problem when changing the background to pure white color (it's was grey). My solutionwas to use the setSearchFieldBackgroundImage. also i don't want to rely on apple struct for getting the UITextField

我尝试了 Daroko 解决方案,但是在将背景更改为纯白色(它是灰色)时遇到了问题。我的解决方案是使用setSearchFieldBackgroundImage。我也不想依赖苹果结构来获取 UITextField

  if #available(iOS 11.0, *) {
     let whiteImage = UIImage(color: UIColor.white, size: CGSize(width: searchController.searchBar.layer.frame.width, height: searchController.searchBar.layer.frame.height))
     searchController.searchBar.setSearchFieldBackgroundImage(whiteImage, for: .normal)
     self.navigationItem.searchController = searchController
     self.navigationItem.hidesSearchBarWhenScrolling = true
 }


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)
} }

I used UIImage extension from : Create UIImage with solid color in Swift

我使用了来自以下内容的 UIImage 扩展: 在 Swift 中创建带有纯色的 UIImage

回答by Alex Kolovatov

In addition to Darko's answer. In my case I need to get pure white search textfield color. Also I need a custom borderLine and cornerRadius. So if I just set background color to white, set custom corner radius and custom border line I've got something like this. Look at this ugly grey highLight when you tap on textfield

除了达科的回答。在我的情况下,我需要获得纯白色的搜索文本字段颜色。另外我需要一个自定义的borderLine和cornerRadius。所以如果我只是将背景颜色设置为白色,设置自定义圆角半径和自定义边框线,我就会得到这样的东西。 当您点击文本字段时,看看这个丑陋的灰色高光

The problem is that the search bar has some subviews and I've just removed them. Here is my code:

问题是搜索栏有一些子视图,我刚刚删除了它们。这是我的代码:

@interface YourViewController () <UISearchBarDelegate, UISearchControllerDelegate>
// your properties
@property (nonatomic,strong) UISearchController *searchController;
@property (nonatomic,strong) UISearchBar *searchBar;
@end

- (void)viewDidLoad {
[super viewDidLoad];

_searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
_searchController.delegate = self;
_searchController.searchBar.delegate = self;
_searchBar = self.searchController.searchBar;

if (@available(iOS 11.0, *)) {

    UITextField *searchTextField = [_searchBar valueForKey:@"searchField"];
if (searchTextField != nil) {
        searchTextField.layer.cornerRadius = 4.f;
        searchTextField.layer.borderWidth = 1.f;
        searchTextField.clipsToBounds = YES;

        for (UIView *subView in searchTextField.subviews) {
            [subView removeFromSuperview];
        }
}

// Color for "Cancel" button
    _searchBar.tintColor = [UIColor blackColor];
// Add searchController to navgationBar
    _navigationItem.searchController = _searchController;
// Hide searchBar when scroll
    _navigationItem.hidesSearchBarWhenScrolling = YES;
}
}

Now I've got a searchBar with pure white background, custom cornerRadius, custom border width. Also I've disabled grey highlight when tap. Editing searchfieldResign first responder

现在我有了一个纯白色背景的搜索栏,自定义的cornerRadius,自定义的边框宽度。此外,我在点击时禁用了灰色突出显示。 编辑搜索栏辞去第一响应者的职务

回答by Marta

This code changes the background color of the text field

此代码更改文本字段的背景颜色

Swift 4

斯威夫特 4

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        //background color of text field
         UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .cyan

        }

edited: sample of a UISearchBar in cyan

编辑:青色 UISearchBar 示例

sample

样本