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

时间:2017-09-01 20:00:42

标签: ios swift uinavigationbar uisearchbar

我想在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
}

正如您在图像中看到的那样,深蓝色背景上的文字是灰色的,看起来很丑陋。我希望文字和图标至少是白色的。 (更改蓝色背景颜色也不起作用,请参阅my other question

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

似乎在iOS 10及以下版本中运行的解决方案在iOS 11中似乎不再有效,所以请仅发布您在iOS 11中工作的解决方案。谢谢。

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

8 个答案:

答案 0 :(得分:100)

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

"取消"文本:

searchController.searchBar.tintColor = .white

搜索图标:

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

清晰的图标:

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

搜索文字:

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

感谢@Brandon的帮助!

enter image description here

占位符:

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

enter image description here

白色背景:

if #available(iOS 11.0, *) {
    let sc = UISearchController(searchResultsController: nil)
    sc.delegate = self
    let scb = sc.searchBar
    scb.tintColor = UIColor.white
    scb.barTintColor = UIColor.white

    if let textfield = scb.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 = sc
    navigationItem.hidesSearchBarWhenScrolling = false
}

enter image description here

取自here

答案 1 :(得分:3)

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

UISearchBar.appearance().tintColor = UIColor.white中的

AppDelegate

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

答案 2 :(得分:3)

设置搜索文本颜色

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

设置搜索占位符颜色

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

答案 3 :(得分:1)

我对Swift 4.x的2美分,轻轻清理了。

添加控制器或应用代理:

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

在控制器中:

self.searchBar.barTintColor = .blue

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

enter image description here

答案 4 :(得分:0)

除了Darko的回答。 在我的情况下,我需要获得纯白色搜索文本字段颜色。 我还需要一个自定义borderLine和cornerRadius。 因此,如果我只是将背景颜色设置为白色,设置自定义角半径和自定义边框线我就有这样的东西。 Look at this ugly grey highLight when you tap on textfield

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

@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;
}
}

现在我有了一个带有纯白色背景,自定义cornerRadius,自定义边框宽度的searchBar。我也点击时禁用了灰色突出显示。 Editing searchfield Resign first responder

答案 5 :(得分:0)

我尝试了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)
} }

我使用了来自的UIImage扩展: Create UIImage with solid color in Swift

答案 6 :(得分:0)

如果有人想知道为什么 Darkos solution 不起作用,请尝试将 UINavigationBar 的样式更改为 { "type": "project", "license": "proprietary", "minimum-stability": "dev", "prefer-stable": true, "require": { "php": ">=7.2.5", "ext-ctype": "*", "ext-iconv": "*", "symfony/console": "5.4.*", "symfony/dotenv": "5.4.*", "symfony/flex": "^1.3.1", "symfony/framework-bundle": "5.4.*", "symfony/runtime": "5.4.*", "symfony/yaml": "5.4.*", "symfony/yaml": "5.4.*", "test/TestBundle": "*" }, "require-dev": { }, "config": { "optimize-autoloader": true, "preferred-install": { "*": "dist" }, "sort-packages": true }, "autoload": { "psr-4": { "App\\": "src/" } }, "autoload-dev": { "psr-4": { "App\\Tests\\": "tests/" } }, "replace": { "symfony/polyfill-ctype": "*", "symfony/polyfill-iconv": "*", "symfony/polyfill-php72": "*" }, "scripts": { "auto-scripts": { "cache:clear": "symfony-cmd", "assets:install %PUBLIC_DIR%": "symfony-cmd" }, "post-install-cmd": [ "@auto-scripts" ], "post-update-cmd": [ "@auto-scripts" ] }, "conflict": { "symfony/symfony": "*" }, "extra": { "symfony": { "allow-contrib": false, "require": "5.4.*" } } } 而不是 default。花了我半天才弄明白¯\_(ツ)_/¯

答案 7 :(得分:-3)

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

Swift 4

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

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

        }

编辑:青色的UISearchBar样本

sample