iOS 7中的UISearchBar文本颜色更改

时间:2013-09-27 10:41:37

标签: ios7 uisearchbar

如何更改UISearchBar中的iOS 7的文字颜色?

iOS 6中,我正在对UISearchBar进行子类化,并在layoutSubviews中自定义UITextField UISearchBar子视图的属性。

但在iOS 7中,UISearchBar没有UITextField作为其子视图。如何解决这个问题?

16 个答案:

答案 0 :(得分:100)

在iOS 7中访问文本字段,您必须在更多级别重申。像这样改变你的代码

for (UIView *subView in self.searchBar.subviews)
{
    for (UIView *secondLevelSubview in subView.subviews){
        if ([secondLevelSubview isKindOfClass:[UITextField class]])
        {
            UITextField *searchBarTextField = (UITextField *)secondLevelSubview;

            //set font color here
            searchBarTextField.textColor = [UIColor blackColor];

            break;
        }
    }
}

注意:这不是公共API

您可以使用UIControls的外观属性,比如

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];

注意:外观代理可用于iOS 9.0+ 输出

enter image description here

您可以将tintcolor设置为应用于search bar

中的关键元素

使用tintColor为前景元素着色。

使用barTintColor为条形背景着色。

在iOS v7.0中,UIView的所有子类都从基类派生出tintColor的行为。有关更多信息,请参阅UIView级别的tintColor讨论。 Apple Doc

答案 1 :(得分:95)

您可以按

设置文字颜色
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor blueColor]];

答案 2 :(得分:35)

对于XCode 6(iOS8 SDK),以下不起作用

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];

但是以下DOES工作(部署到iOS7和iOS8)

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];

答案 3 :(得分:5)

虽然UIAppearance协议确实是“公共API”,但UITextField支持这一点并不正确。

如果您查看UITextField.h并查找字符串“UI_APPEARANCE_SELECTOR”,您将看到它没有此字符串的实例。如果你看看UIButton,你会发现很多 - 这些都是UIAppearance API官方支持的所有属性。众所周知UIAextField不受UIAppearance API的支持,因此Sandeep的答案中的代码并不总是有效,而且实际上并不是最好的方法。

这是一篇有用链接的有用帖子:http://forums.xamarin.com/discussion/175/uitextfield-appearance

不幸的是,正确的方法很麻烦 - 遍历子视图(或iOS7主要子视图的子视图)并手动设置。否则你将得到不可靠的结果。但是你可以为UISearchBar创建一个类别并添加一个setTextColor:(UIColor *)颜色方法。例如:

- (void)setTextColor:(UIColor*)color
{
    for (UIView *v in self.subviews)
    {
        if([Environment isVersion7OrHigher]) //checks UIDevice#systemVersion               
        {
            for(id subview in v.subviews)
            {
                if ([subview isKindOfClass:[UITextField class]])
                {
                    ((UITextField *)subview).textColor = color;
                }
            }
        }

        else
        {
            if ([v isKindOfClass:[UITextField class]])
            {
                ((UITextField *)v).textColor = color;
            }
        }
    }
}

答案 4 :(得分:5)

警告:这会导致应用拒绝!

KVC FTW。这样做对我来说。

UITextField *searchField = [self.searchBar valueForKey:@"_searchField"];
searchField.textColor = [UIColor redColor];

答案 5 :(得分:4)

您可以像这样设置文本属性

[[UITextField appearanceWhenContainedIn:[<YOUR_CONTROLLER_NAME> class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:14.0]}];

答案 6 :(得分:4)

以下是使用Xamarin在C#中完成的工作示例:

SearchBar = new UISearchBar ();
foreach (var subView in SearchBar.Subviews) {
    foreach (var field in subView.Subviews) {
        if (field is UITextField) {
            UITextField textField = (UITextField)field;
            textField.TextColor = UIColor.White;
        }
    }
}

希望这有助于某人。

答案 7 :(得分:4)

这似乎是正确答案https://stackoverflow.com/a/19315895/2493073

它的Swift版本是:

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.blueColor()

这仅适用于iOS 9.0 ,为了使其适用于较低版本,您需要遵循此问题。 https://stackoverflow.com/a/27807417/2493073

答案 8 :(得分:4)

快速扩展

public extension UISearchBar {

    public func setTextColor(color: UIColor) {
        let svs = subviews.flatMap { $0.subviews }
        guard let tf = (svs.filter { $0 is UITextField }).first as? UITextField else { return }
        tf.textColor = color
    }
}

答案 9 :(得分:2)

就我而言,我有多个UISearchBar个对象,他们需要更改textField字体颜色。 appearanceWhenContainedIn更新了一个UISearchBar行为,但另一个行为没有。

我将UISearchBar子类化并实现自定义-(id)initWithFrame:,如下所示,它可以正常工作。

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.searchBarStyle       = UISearchBarStyleMinimal;
        self.tintColor            = [UIColor whiteColor];
        self.barTintColor         = [UIColor whiteColor];

        [[UITextField appearanceForTraitCollection:self.traitCollection whenContainedIn:[self class], nil] setDefaultTextAttributes:
         @{
           NSForegroundColorAttributeName : [UIColor whiteColor]
           }];
    }
    return self;
}

UIAppearance Protocol Reference说,

  

换句话说,收录声明   appearanceWhenContainedIn:被视为部分排序。给出一个   具体排序(实际的子视图层次结构),UIKit选择   部分排序是读取时的第一个唯一匹配   从窗口向下的实际层次结构。

因此,appearanceWhenContainedIn:无法处理UISearchBar层次结构中的所有UIWindow。它表明了这一点。

  

使用appearanceForTraitCollection:和   appearanceForTraitCollection:whenContainedIn:检索方法   具有指定特征集合的类的代理。

答案 10 :(得分:1)

最简单的方法是将此代码放在viewDidAppear或viewWillAppear 中:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];

这适用于iOS 8和Xcode 6 ,与其他一些代码不同。它可以搞乱字体和文本大小等,但您可以在文本属性中更改它。

这会更改应用中所有搜索栏的文字颜色。如果您只想更改一个,请使用上面的代码,然后在任何其他视图中使用搜索栏,使用相同的代码,但将颜色设置为您想要的颜色。

答案 11 :(得分:1)

您可以在文本字段中使用搜索栏

 UISearchBar *  searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 50, 320, 44) ];
searchBar.autocorrectionType = UITextAutocapitalizationTypeWords;
searchBar.delegate = self;
searchBar.searchBarStyle = UISearchBarStyleMinimal;
searchBar.barTintColor = [UIColor redColor];
[[UITextField appearanceWhenContainedIn:[searchBar class], nil]setDefaultTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
[self.view addSubview:searchBar];

答案 12 :(得分:1)

Swift 3中的更新

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.black

答案 13 :(得分:0)

尽管我更喜欢使用外观API,但它并不适用于iOS8。这是我带来的最不具体的解决方案:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if (self.shouldEnableSearchBar)
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^
        {
            UITextField *searchBarTextField = [[AFPBaseViewController findSubviewsOfView:self.searchBar ofClass:[UITextField class]] firstObject];
            searchBarTextField.textColor = AFPConstantsColorGold;
        });
    }

}

你甚至可以用它来创建一个UIView类别。必须在viewDidAppear中调用它的原因是UISearchBar实际上包含在ViewController中,并且在它出现在屏幕上之前不会加载其所有子视图。它也可以添加到viewWillAppear中,但我还没有测试过它。

+ (NSArray *)findSubviewsOfView:(UIView *)view ofClass:(Class)class
{
    NSMutableArray *targetSubviews = [NSMutableArray new];
    for (id subview in view.subviews)
    {
        if ([subview isKindOfClass:class])
        {
            [targetSubviews addObject:subview];
        }

        if ([subview subviews].count)
        {
            [targetSubviews addObjectsFromArray:[self findSubviewsOfView:subview ofClass:class]];
        }
    }
    return targetSubviews.copy;
}

答案 14 :(得分:0)

这是iOS8的正确解决方案:

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:14], NSForegroundColorAttributeName:[UIColor lightGrayColor]}];

您还必须设置字体,否则字体大小将会出错。

答案 15 :(得分:0)

此课程将让您完全控制UISearchBar

中的每个项目
import UIKit

class SMTSearchBar: UISearchBar {

    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        initialize()
    }

    convenience init() {
        self.init(frame: CGRectZero)
        initialize()
    }

    // Style the view
    func initialize() {

        // Search Area
        let searchField = valueForKey("searchField") as! UITextField
        searchField.textColor = Colors.White
        searchField.font = UIFont(name: Fonts.MuseoSans500, size: 16)
        searchField.backgroundColor = Colors.Black.colorWithAlphaComponent(0.1)

        // Icons
        let searchIcon = UIImage(named: Icons.Search)?.imageWithTint(Colors.White)
        let smallClearIconNormal = UIImage(named: Icons.SmallClear)?.imageWithTint(Colors.White)
        let smallClearIconHighLight = UIImage(named: Icons.SmallClear)?.imageWithTint(Colors.White.colorWithAlphaComponent(0.5))
        setImage(searchIcon, forSearchBarIcon: .Search, state: .Normal)
        setImage(smallClearIconHighLight, forSearchBarIcon: .Clear, state: .Highlighted)
        setImage(smallClearIconNormal, forSearchBarIcon: .Clear, state: .Normal)
    }

    func setPlaceHolder(placeholder: String) {
        for subView in subviews{
            for subsubView in subView.subviews {
                if let textField = subsubView as? UITextField {
                    textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: Colors.White.colorWithAlphaComponent(0.5)])
                }
            }
        }
    }
}

用法(在导航栏中)

let searchBar:SMTSearchBar = SMTSearchBar()
searchBar.sizeToFit()
searchBar.setPlaceHolder("Search for cool things")
navigationItem.titleView = searchBar
searchBar.becomeFirstResponder()