我正在自定义搜索栏并努力改变"取消"的字体。在搜索栏中键入时弹出的按钮。到目前为止,这是我尝试的(将UIView转换为UIBarButton失败):
for subView in controller.searchBar.subviews {
if let cancelButton = subView as? UIBarButtonItem {
cancelButton.setTitleTextAttributes([ NSFontAttributeName: font ], forState: UIControlState.Normal)
}
}
答案 0 :(得分:1)
迅速:
if #available(iOS 9.0, *) {
UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(15, weight: UIFontWeightLight)], forState: .Normal)
} else {
// Fallback on earlier versions
}
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];
答案 1 :(得分:0)
在包含搜索栏的视图中,例如:
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
// ...
override func viewDidLoad() {
super.viewDidLoad()
// ... other init code
// search bar "Cancel" color
searchBar.tintColor = UIColor.redColor();
// search bar "Cancel": custom text and font
for sView in searchBar.subviews {
for ssView in sView.subviews {
if ssView.isKindOfClass(UIButton.self) {
let cancelButton = ssView as! UIButton
cancelButton.setTitle("Custom", forState: .Normal)
cancelButton.titleLabel?.font = UIFont(name: "GillSans-BoldItalic", size: 14.0)
break
}
}
}
}
// ...
}
对于不同的字体,请参阅http://iosfonts.com,有关颜色,请参阅UIColor Class Reference。