在UISearchBar问题中取消按钮

时间:2015-06-24 10:21:39

标签: ios objective-c iphone xcode uisearchbar

我已在我的应用中使用自定义(本地化)标题实现了搜索栏。

我第一次点按搜索时会显示取消按钮,如下所示:

第一次

enter image description here

第二次当我按下取消按钮&再次点击搜索栏,它看起来很好。

enter image description here

我的代码

   - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{

    [searchBar setShowsCancelButton:YES animated:YES];


    UIButton *cancelButton;
    UIView *topView = search.subviews[0];
    for (UIView *subView in topView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            cancelButton = (UIButton*)subView;
        }
    }
    if (cancelButton) {
        [cancelButton setTitle:Localized(@"Cancel") forState:UIControlStateNormal];
    }

}

3 个答案:

答案 0 :(得分:2)

这对我有用:

if (cancelButton) {
    [cancelButton setTitle:Localized(@"Cancel") forState:UIControlStateNormal];
    [search setNeedsLayout];
    [search layoutIfNeeded];
}

答案 1 :(得分:2)

尝试使用NSLocalizedString设置UIAppearance

[[UIButton appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:Localized(@"Cancel") forState:UIControlStateNormal];

答案 2 :(得分:0)

我在swift 4中翻译了Jasper答案:

UIButton.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitle("Cancel", for: .normal)