修改UISearchBar取消按钮字体文本颜色和样式

Row*_* Po 20 uisearchbar ios

有没有办法更改UISearchBar取消按钮的文本字体和颜色而无需继承搜索栏?

hti*_*inn 69

您可以通过更改UIBarButtonItem包含时的外观来更改"取消"按钮样式UISearchBar.

例如,

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                      [UIColor blueColor], 
                                                      UITextAttributeTextColor, 
                                                      [UIColor darkGrayColor], 
                                                      UITextAttributeTextShadowColor, 
                                                      [NSValue valueWithUIOffset:UIOffsetMake(0, -1)], 
                                                      UITextAttributeTextShadowOffset,
                                                      nil] 
                                            forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

  • 这是我可以在任何地方找到的关于这个主题的最佳答案. (5认同)
  • 那些只想设置自定义UISearchBar cacel按钮颜色的人使用tintColor [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class],nil] setTintColor:[UIColor redColor]]; (4认同)
  • 为了设置字体样式和大小,我使用了这样的东西:`[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class],nil] setTitleTextAttributes:@ {NSFontAttributeName:[UIFont fontWithName:@"SourceSansPro-Regular"size:14]} forState :UIControlStateNormal];` (2认同)

Chr*_*irk 15

斯威夫特3

let attributes = [
    NSForegroundColorAttributeName : UIColor.white,
    NSFontAttributeName : UIFont.systemFont(ofSize: 17)
]
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(attributes, for: .normal)
Run Code Online (Sandbox Code Playgroud)


Jav*_*cio 11

斯威夫特 5

let attributes:[NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.black,
    .font: UIFont.systemFont(ofSize: 17)
]
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(attributes, for: .normal)
Run Code Online (Sandbox Code Playgroud)


eMd*_*dOS 6

如果您只想修改取消按钮,可以通过以下方式进行:

if let cancelButton = searchBar.valueForKey("cancelButton") as? UIButton {
    cancelButton.setTitle(<your_string>, forState: <UIControlState>)
    cancelButton.setTitleColor(<your_uicolor>, forState: <UIControlState>)
    cancelButton.setAttributedTitle(<your_nsattributedstring>, forState: <UIControlState>)
}
Run Code Online (Sandbox Code Playgroud)

searchBar你的UISearchBar对象在哪里。


dan*_*elM 5

基于 htinlinn 的回答,这是我在viewDidLoad使用 iOS 7 中的搜索栏的视图控制器方法中使用的:

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil]
                     setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil] 
                                   forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)