更改UISearchBar /键盘搜索按钮标题

Jim*_*m B 54 iphone button title uisearchbar

在UISearchBar控件中,是否可以将键盘的搜索键标题更改为"完成"?

Run*_*oop 99

对于名为tablesearchbar的搜索栏:

// Set the return key and keyboard appearance of the search bar
        for (UIView *searchBarSubview in [tableSearchBar subviews]) {

            if ([searchBarSubview conformsToProtocol:@protocol(UITextInputTraits)]) {

                @try {

                    [(UITextField *)searchBarSubview setReturnKeyType:UIReturnKeyDone];
                    [(UITextField *)searchBarSubview setKeyboardAppearance:UIKeyboardAppearanceAlert];
                }
                @catch (NSException * e) {

                    // ignore exception
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • 循环子视图在iOS 7中对我不起作用,但循环子视图的子视图(参见我的回答). (6认同)
  • 由于没有访问私有API,因此不应拒绝批准 (4认同)
  • 很好的答案.额外警告:不是使用@ try- @ catch(我们在Objective-C中知道它们并不那么便宜且经过优化),我宁愿在if语句中添加第二个条件:&& [searchBarSubview isKindOfClass:[UITextField class] ]为了摆脱@ try-catch. (2认同)

pic*_*ick 48

至少对于iOS 8,简单地说:

    [self.searchBar setReturnKeyType:UIReturnKeyDone];
Run Code Online (Sandbox Code Playgroud)


Gre*_*aun 43

从iOS 7 beta 5开始,Run Loop的回答对我不起作用,但是这样做了:

for(UIView *subView in [searchBar subviews]) {
    if([subView conformsToProtocol:@protocol(UITextInputTraits)]) {
         [(UITextField *)subView setReturnKeyType: UIReturnKeyDone];
    } else {
        for(UIView *subSubView in [subView subviews]) {
            if([subSubView conformsToProtocol:@protocol(UITextInputTraits)]) {
                [(UITextField *)subSubView setReturnKeyType: UIReturnKeyDone];
            }
        }      
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果不清楚,使用if/else的原因是if是针对iOS 6的向后兼容性而else是针对iOS 7的. (5认同)

the*_*ker 18

一个更有用的提示,运行循环代码(在"@try")部分.

当文本字段为空时,这会启用"完成"按钮:

UITextField *tf = (UITextField *)searchBarSubview;
tf.enablesReturnKeyAutomatically = NO;
Run Code Online (Sandbox Code Playgroud)


Har*_*kar 13

为Swift更改UISearchBar的返回键

searchBar.returnKeyType = UIReturnKeyType.done
Run Code Online (Sandbox Code Playgroud)

枚举可用如下

public enum UIReturnKeyType : Int {

    case default
    case go
    case google
    case join
    case next
    case route
    case search
    case send
    case yahoo
    case done
    case emergencyCall
    @available(iOS 9.0, *)
    case continue
}
Run Code Online (Sandbox Code Playgroud)