ios 如何更改出现在 UISearchBar +iPhone 中的取消按钮的默认文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2536151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:04:56  来源:igfitidea点击:

How to change the default text of Cancel Button which appears in the UISearchBar +iPhone

iosiphoneuisearchbar

提问by Pradeep Reddy Kypa

I am developing an Application where I wanted to change the text of Search String in the SearchBar. I wanted to change the text of Cancel Button Also which appears next to the SearchBar. Before entering any string in the search bar we wil get the Search String as the default string. I wanted to change the text of that string and when we click on that searchbar we get a cancel button next to searchbar and I wanted to change the text of that cancel button.

我正在开发一个应用程序,我想在其中更改 SearchBar 中搜索字符串的文本。我想更改出现在 SearchBar 旁边的 Cancel Button Also 的文本。在搜索栏中输入任何字符串之前,我们将获得搜索字符串作为默认字符串。我想改变这种字符串的文本,当我们点击该搜索栏,我们得到一个取消旁边的搜索栏按钮,我想改变这种状况的取消按钮上的文本。

回答by Yariv Nissim

Use the appearance proxy:

使用外观代理:

id barButtonAppearanceInSearchBar = [UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil];

[barButtonAppearanceInSearchBar setBackgroundImage:grayBackgroundImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[barButtonAppearanceInSearchBar setTitleTextAttributes:@{
                                      NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:20],
                                 NSForegroundColorAttributeName : [UIColor blackColor]
     } forState:UIControlStateNormal];
[barButtonAppearanceInSearchBar setTitle:@"X"];

回答by David Brownstone

You also need to have the "searchBar setShowsCancelButton" before the procedure.

您还需要在程序之前设置“searchBar setShowsCancelButton”。

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    [theSearchBar setShowsCancelButton:YES animated:NO];
    for (UIView *subView in theSearchBar.subviews){
        if([subView isKindOfClass:[UIButton class]]){
            [(UIButton*)subView setTitle:@"Done" forState:UIControlStateNormal];
        }
    }
}

Note also: use UIButton to avoid problems with Apple!

另请注意:使用 UIButton 可避免 Apple 出现问题!

回答by SGI

Solution for iOS 7. All credits for this go to Mr. Jesper Nielsen- he wrote the code.

适用于 iOS 7 的解决方案。所有功劳都归功于Jesper Nielsen 先生- 他编写了代码。

-(void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
    UIButton *cancelButton;
    UIView *topView = theSearchBar.subviews[0];
    for (UIView *subView in topView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            cancelButton = (UIButton*)subView;
        }
    }
    if (cancelButton) {
        [cancelButton setTitle:@"YourTitle" forState:UIControlStateNormal];
    }

}

回答by glorifiedHacker

If by "Search String", you mean the placeholder, then this should do it:

如果“搜索字符串”是指占位符,那么应该这样做:

[searchBar setPlaceholder:@"Whatever you want"];

As for changing the text of the cancel button, that may be a bit more difficult. Apple does not use a standard UIBarButtonItem for this, or even a non-standard UIButton. Instead they use a UINavigationButton for the cancel button in the search bar. Since this is not a documented public class, attempting to modify it could very well get your app rejected from the App Store. If you do want to risk rejection, then you could search through the subviews of searchBar:

至于更改取消按钮的文本,那可能有点困难。Apple 没有为此使用标准的 UIBarButtonItem,甚至没有使用非标准的 UIButton。相反,他们使用 UINavigationButton 作为搜索栏中的取消按钮。由于这不是记录在案的公共类,因此尝试修改它很可能会使您的应用程序被 App Store 拒绝。如果您确实想冒被拒绝的风险,那么您可以搜索 searchBar 的子视图:

for(UIView *view in [searchBar subviews]) {
    if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
        [(UIBarItem *)view setTitle:@"Whatever you want"];
    }
}

Note that the cancel button is loaded lazily, so you will have to do this modification when the search bar is activated by the user.

请注意,取消按钮是延迟加载的,因此您必须在用户激活搜索栏时进行此修改。

回答by Maishi Wadhwani

In iOS 7 if you are using UISearchBar just write this code in searchBarTextDidBeginEditing: method

在 iOS 7 中,如果您使用 UISearchBar 只需在 searchBarTextDidBeginEditing: 方法中编写此代码

searchBar.showsCancelButton = YES;UIView* view=searchBar.subviews[0];
for (UIView *subView in view.subviews) {
      if ([subView isKindOfClass:[UIButton class]]) {
          UIButton *cancelButton = (UIButton*)subView;

          [cancelButton setTitle:@"?????" forState:UIControlStateNormal];
       }
}

回答by C?ur

I would like to fix the UIAppearance technique, as yar1vn code won't work with Xcode 5. With the following you will have code that works perfectly for both iOS 6 and iOS 7.

我想修复 UIAppearance 技术,因为 yar1vn 代码不适用于 Xcode 5。通过以下内容,您将拥有适用于 iOS 6 和 iOS 7 的代码。

First, you need to understand that the cancel button is a private UINavigationButton:UIButton. Hence, it is not an UIBarButtonItem. After some inspection, it appears that UINavigationButton will respond to those UIAppearance selectors:

首先,您需要了解取消按钮是一个私有的 UINavigationButton:UIButton。因此,它不是 UIBarButtonItem。经过一些检查,似乎 UINavigationButton 会响应那些 UIAppearance 选择器:

// inherited from UINavigationButton
@selector(setTintColor:)
@selector(setBackgroundImage:forState:style:barMetrics:)
@selector(setBackgroundImage:forState:barMetrics:)
@selector(setTitleTextAttributes:forState:)
@selector(setBackgroundVerticalPositionAdjustment:forBarMetrics:)
@selector(setTitlePositionAdjustment:forBarMetrics:)
@selector(setBackButtonBackgroundImage:forState:barMetrics:)
@selector(setBackButtonTitlePositionAdjustment:forBarMetrics:)
@selector(setBackButtonBackgroundVerticalPositionAdjustment:forBarMetrics:)

// inherited from UIButton
@selector(setTitle:forState:)

Coincidentally, those selectors match those of a UIBarButtonItem. Meaning the trick is to use two separate UIAppearance to handle the private class UINavigationButton.

巧合的是,这些选择器与 UIBarButtonItem 的选择器相匹配。这意味着技巧是使用两个单独的 UIAppearance 来处理私有类 UINavigationButton。

/* dual appearance technique by C?ur to customize a UINavigationButton */
Class barClass = [UISearchBar self];

UIBarButtonItem<UIAppearance> *barButtonItemAppearanceInBar = [UIBarButtonItem appearanceWhenContainedIn:barClass, nil];
[barButtonItemAppearanceInBar setTintColor:...];
[barButtonItemAppearanceInBar setBackgroundImage:... forState:... style:... barMetrics:...];
[barButtonItemAppearanceInBar setBackgroundImage:... forState:... barMetrics:...];
[barButtonItemAppearanceInBar setTitleTextAttributes:... forState:...];
[barButtonItemAppearanceInBar setBackgroundVerticalPositionAdjustment:... forBarMetrics:...];
[barButtonItemAppearanceInBar setTitlePositionAdjustment:... forBarMetrics:...];
[barButtonItemAppearanceInBar setBackButtonBackgroundImage:... forState:... barMetrics:...];
[barButtonItemAppearanceInBar setBackButtonTitlePositionAdjustment:... forBarMetrics:...];
[barButtonItemAppearanceInBar setBackButtonBackgroundVerticalPositionAdjustment:... forBarMetrics:...];

UIButton<UIAppearance> *buttonAppearanceInBar = [UIButton appearanceWhenContainedIn:barClass, nil];
[buttonAppearanceInBar setTitle:... forState:...];

Now, this technique works for the Cancel button, but it also works for the Back button if you change the barClass to [UINavigationBar self].

现在,此技术适用于取消按钮,但如果将 barClass 更改为 ,它也适用于后退按钮[UINavigationBar self]

回答by Alexander Karpov

This solution work for me - iOs7 and iOs8:

这个解决方案对我有用 - iOs7 和 iOs8:

@interface ... : ...
@property (strong, nonatomic) IBOutlet UISearchBar *search; 
@end

and

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[searchBar setShowsCancelButton:YES animated:YES];

NSArray *searchBarSubViews = [[self.search.subviews objectAtIndex:0] subviews];
UIButton *cancelButton;
for (UIView *subView in searchBarSubViews) {
    if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
        cancelButton = (UIButton*)subView;
        break;
    }
}
if (cancelButton) {

    [cancelButton setTitle:@"New cancel" forState:UIControlStateNormal];

}
 //insert this two lines below if you have a button appearance like this "Ne...cel" 

[searchBar setShowsCancelButton:NO animated:YES];
[searchBar setShowsCancelButton:YES animated:YES]; 
}

回答by WizMeister

Jeremytripp 's working Code in Swift

Jeremytripp 在 Swift 中的工作代码

I couldn't find the same code in Swift so I "translated" it myself:

我在 Swift 中找不到相同的代码,所以我自己“翻译”了它:

func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
    self.searchDisplayController?.searchBar.showsCancelButton = true
    var cancelButton: UIButton
    var topView: UIView = self.searchDisplayController?.searchBar.subviews[0] as UIView
    for subView in topView.subviews {
        if subView.isKindOfClass(NSClassFromString("UINavigationButton")) {
        cancelButton = subView as UIButton
        cancelButton.setTitle("My Custom Title", forState: UIControlState.Normal)
        }
    }
}

回答by Itachi

If you just want to localizedthe default "Cancel" title for cancel button, I prefer to change the value of CFBundleDevelopmentRegionkey from en to your localized region in Info.plist file in project.

如果您只想本地化取消按钮的默认“取消”标题,我更喜欢将CFBundleDevelopmentRegion键的值从 en更改为项目中 Info.plist 文件中的本地化区域。

Here is my change,

这是我的变化,

<key>CFBundleDevelopmentRegion</key>
<string>zh_CN</string>

after that, the default "Cancel" title will show as Chinese "取消". This change will also affect all the default region values, for example, the pasteboard operations' action titles on UITextField/UITextView will be localized, "Select" -> "选择", "Paste" -> "粘贴"...

之后,默认的“取消”标题将显示为中文“取消”。此更改也会影响所有默认区域值,例如 UITextField/UITextView 上粘贴板操作的动作标题将被本地化,“选择”->“选择”,“粘贴”->“粘贴”...

By the way, the Info.plist file could be localized perfectly.

顺便说一下,Info.plist 文件可以完美地本地化。

Enjoy!

享受!

回答by followben

On iOS 7, if you've set displaysSearchBarInNavigationBar = YESon UISearchDisplayController, replacing the cancel button title via subview recursion or the appearance proxy will not work.

在iOS 7,如果你设置displaysSearchBarInNavigationBar = YESUISearchDisplayController,免去了通过子视图递归或外观代理取消按钮标题将无法正常工作

Instead, use your own bar button in viewDidLoad:

相反,在 中使用您自己的条形按钮viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.searchDisplayController.displaysSearchBarInNavigationBar = YES;
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"A Custom Title", nil)
                                                                style:UIBarButtonItemStyleBordered
                                                               target:self
                                                               action:@selector(cancelButtonTapped:)];

    // NB: Order is important here.
    //     Only do this *after* setting displaysSearchBarInNavigationBar to YES
    //     as that's when UISearchDisplayController creates it's navigationItem
    self.searchDisplayController.navigationItem.rightBarButtonItem = barItem;
}