更改UISearchBar取消按钮的字体样式

时间:2016-06-10 18:49:28

标签: swift

我正在尝试将UISearchBar取消按钮的字体更改为' OpenSans'但我无法访问任何属性。我只能更改UISearchBar的色调颜色,它会改变搜索栏取消按钮文本和颜色的颜色。搜索栏UITextField游标颜色:

searchBar.tintColor = UIColor(red: 187.0/255.0, green: 187.0/255.0, blue: 187.0/255.0, alpha: 1.0)

有没有办法实现这个目标?

4 个答案:

答案 0 :(得分:7)

尝试这样的事情对我有用。

 UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont(name: "OpenSans", size: 15)!], forState: .Normal)

如果您想更改颜色,请将其添加到您的属性数组中。

 NSForegroundColorAttributeName : UIColor.whiteColor()

注意:在iOS 9中提供

答案 1 :(得分:4)

这适用于Swift 3.0

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont(name: "OpenSans", size: 15)!], for: .normal)

答案 2 :(得分:0)

swift 2:

if #available(iOS 9.0, *) {
     UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(15, weight: UIFontWeightLight)], forState: .Normal)
} else {
     // Fallback on earlier versions
}

swift3:

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont(name: "OpenSans", size: 15)!], for: .normal)

Objective-C:

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

答案 3 :(得分:0)

Swift 4.2

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedString.Key.font : UIFont(name: "your_font_name", size: 16)!], for: .normal)