2017-08-14 89 views
0

UISearchbar add navigationController?.navigationBar。如何更改“取消”颜色UISearchbar add navigationController?.navigationBar,如何更改“取消”颜色

_searchBar = UISearchBar(frame: CGRect(frame: CGRect(x: 0, y: 0, width: 414, height: 64))) 
_searchBar!.delegate = self 
_searchBar!.showsCancelButton = true 
backgroundColor = .white 
barTintColor = .white 
tintColor = .red 
backgroundImage = UIImage() 
_searchBar!.placeholder = "搜索文件" 
navigationController?.navigationBar.addSubview(_searchBar!) 

此结果是“取消”颜色为白色。我如何将它设置为红色?

+0

看到这个曾经https://stackoverflow.com/questions/35302760/如何改变取消按钮上的uisearchbar-in-swift –

回答

0

使用appearance功能UIAppearance模块 -

方法1: -可见取消按钮的颜色,当searchBar上负载

let attributes = [NSForegroundColorAttributeName : UIColor.red] 
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes(attributes, for: .normal) 

或 -

方法2: - 可见取消按钮颜色searchBar点击后 -

UIBarButtonItem.appearance(whenContainedInInstancesOf:[UISearchBar.self]).tintColor = UIColor.red 
+0

@ Jack非常感谢你,这是工作,但它必须iOS9.0,​​@ Anbu.Karthink答案适用于t o所有系统版本 –

0

cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: ``UIColor.YOUR COLOR] UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as?[String : AnyObject], forState: UIControlState.Normal)

+0

在你的地方你的颜色ADD UIColor.YOUR COLOR –

0

改变了格式可读性

let cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: UIColor.YOUR COLOR]  UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as? [String : AnyObject], forState: UIControlState.Normal)