如果在 viewDidAppear 之前显示,UISearchBar 取消按钮没有样式

UISearchBar cancel button not styled if displayed before viewDidAppear

我正在像这样设置取消按钮的色调:

[UIBarButtonItem appearance].tintColor = [UIColor highlightedTextColor];

如果在 viewDidAppear 之后或期间显示取消按钮,效果会很好,例如如果搜索栏获得焦点时显示取消:

但是,如果之前执行过此操作,例如在 viewDidLoad 甚至在 viewWillAppear:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.searchBar setShowsCancelButton:YES animated:NO];
}

那么结果就不太好了:

文字确实存在,尽管使用色度计只能检测到非常微弱的阴影。 有没有其他人遇到过这个问题并找到了解决方案? 我能找到的最好的一个是在 viewDidAppear.

中显示取消按钮

对我来说效果很好,我在 UIView 中创建了 UISearchBar。 viewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10.0f, 0.0f, self.view.bounds.size.width-20, 44.0f)];
    _searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _searchBar.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _searchBar.showsCancelButton = YES;
    //_searchBar.searchBarStyle = UISearchBarStyleMinimal;
    [_searchBar sizeToFit];
    [_searchBar becomeFirstResponder];
    _searchBar.delegate = self;
    _searchBar.barTintColor = color;
    _searchBar.tintColor = color;
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                                              [UIColor whiteColor],
                                                                                              NSForegroundColorAttributeName,
                                                                                              nil]
                                                                                    forState:UIControlStateNormal];
    _barWrapper = [[UIView alloc]initWithFrame:self.navigationController.navigationBar.bounds];
    [_barWrapper addSubview:_searchBar];
    _barWrapper.autoresizingMask = UIViewAutoresizingFlexibleWidth;
}

在 viewWillAppear 中,我将 barWrapper 放在导航栏中。

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:_barWrapper];
    [_searchBar becomeFirstResponder];
}

最后,在 viewWillDisappear 中,我从导航栏中删除了 barWrapper。

- (void)viewWillDisappear:(BOOL)animated{
    [_barWrapper removeFromSuperview];
}