【问题标题】:how to change UISearchBar textfield background color and text color in ios8如何在 ios8 中更改 UISearchBar 文本字段背景颜色和文本颜色
【发布时间】:2016-11-12 07:01:03
【问题描述】:

我使用下面的代码来更改 UISearchBar 文本字段的背景颜色。

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

但这对我不起作用,任何人都可以提供解决方案。 提前致谢

【问题讨论】:

  • 您能否添加更多信息“它对我不起作用”非常模糊。
  • 你能举个例子在uisearchbar中设置文本字段背景颜色

标签: objective-c ios8


【解决方案1】:

试试这个:

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];

【讨论】:

  • 它给了我异常错误“这个类不符合键搜索字段的键值编码”
  • 虽然这是一篇较老的帖子,但我认为valueForKey arg 应该是@"_searchField",这样就不会出现KVC 错误。
【解决方案2】:

试试这段代码

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

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多