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

标签 ios objective-c uisearchbar uiappearance

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

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

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

Cancel button properly styled

但是,如果这是之前执行的,例如在 viewDidLoad 中甚至在 viewWillAppear 中:

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

那么结果就不那么好了:

Cancel not styled

文字确实存在,尽管使用色度计只能检测到非常微弱的阴影。 有没有其他人遇到过这个问题并找到了解决方案? 我能找到的最好的方法是在 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];
}

关于ios - 如果在 viewDidAppear 之前显示,UISearchBar 取消按钮没有样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35438238/

相关文章:

ios - 更改 UITabBar 高度

objective-c - 如何将 NSMutableString 转换为常规 NSString?

ios - UISearchBar搜索功能不起作用

ios - 更改文本后无法更改 UISearchBar 取消按钮标题颜色。

ios - iPhone Safari 书签创建新 session

ios facebook 获取玩相同应用程序的好友列表

objective-c - KVC 使用哪种方法?

ios - -[__NSCFArray objectForKey :]: unrecognized selector sent to instance 0x11c824e0

ios - 快速添加范围栏

ios - 持续扫描 iOS CoreBluetooth Central Manager?