如何在iOS8中更改UISearchBar文本框的背景颜色和文本颜色

12

我使用以下代码来更改UISearchBar文本框的背景颜色。

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:@{
                                                                   NSForegroundColorAttributeName : [UIColor redColor],
                                                                     NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                            }];
但是这对我没有用,有人可以给出解决方案吗?先感谢了。

你能否提供更多信息?“它对我无效”这样的描述过于模糊。 - potame
你能否提供在 UISearchBar 中设置 TextField 背景颜色的示例? - Vishnu
2个回答

22

试试这个:

UITextField *searchField = [self.searchBar valueForKey:@"searchField"];

// To change background color
searchField.backgroundColor = [UIColor blueColor];

// To change text color
searchField.textColor = [UIColor redColor];

// To change placeholder text color
searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Some Text"];
UILabel *placeholderLabel = [searchField valueForKey:@"placeholderLabel"];
placeholderLabel.textColor = [UIColor grayColor];

它给我抛出了异常错误:“此类不符合键值编码的搜索字段”。 - Yusuf Kamil AK
虽然这是一个较旧的帖子,但我认为 valueForKey 参数应该为 @"_searchField",这样您就不会收到 KVC 错误。 - archsten

12

只需尝试此代码

[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor grayColor]];

或者

试试这个

- (void)viewDidLoad
    {
        [super viewDidLoad];

        //change the background color

 [[self searchViewForTextFieldBg:self.searchTextfield] setBackgroundColor:[UIColor grayColor]];

//change the textcolor
self.searchTextfield.textColor =[UIColor greenColor];

    }

    - (UITextField*)searchViewForTextFieldBg:(UIView*)view
{
    if ([view isKindOfClass:[UITextField class]]) {
        return (UITextField*)view;
    }
    UITextField *searchTextField;
    for (UIView *subview in view.subviews) {
        searchTextField = [self searchViewForTextFieldBg:subview];
        if (searchTextField) {
            break;
        }
    }
    return searchTextField;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接