UITextField 外观在 UISearchBar 中不起作用

And*_*kha 5 objective-c uitextfield uisearchbar ios uiappearance

我正在尝试为搜索栏中的文本字段设置背景颜色。起初我是这样做的:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].backgroundColor = [UIColor blueColor];

    return YES;
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用。颜色保持白色。好的。我通过调用以下代码使其工作:

UISearchBar* searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];

self.tableView.tableHeaderView = searchBar;

[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]].backgroundColor = [UIColor blueColor];
Run Code Online (Sandbox Code Playgroud)

viewDidLoad。但它只能工作一次。当打开此类的另一个视图控制器时,背景颜色保持不变。

你可以自己尝试一下。只需创建一个简单的 iOS 应用程序模板并添加UISearchBar. 然后尝试通过设置其文本字段的背景颜色UIAppearance

怎么了?这是 iOS 的 bug 吗?我知道我可以遍历搜索栏的所有子视图,查找UITextField并设置其背景颜色,但我想知道发生了什么。