![](/img/trans.png)
[英]How can I change the color of UISearchBar “cancel” button in Swift 3?
[英]How to change color of cancel button in UISearchBar
在自定義類上設置barTintColor
屬性時,取消按鈕不可見! 它在那里,但不可見。 我的最低兼容性是iOS 8.0,因此我無法使用appearance(whenContainedInInstancesOf: <#T##[UIAppearanceContainer.Type]#>)
而且我還嘗試了循環遍歷子視圖並設置tintColor
但那也不起作用。 我不能使用UIBarButtonItem.appearance().tintColor
因為我的場景中有一個工具欄,這也會更改其他按鈕的tintColor。
顏色代碼是:
static let purpleColor = UIColor(red: CGFloat(70.0/255.0), green: CGFloat(54.0/255.0), blue: CGFloat(224.0/255.0), alpha: CGFloat(1.0))
static let scrollBackgroundColor = UIColor(red: CGFloat(240.0/255.0), green: CGFloat(241.0/255.0), blue: CGFloat(242.0/255.0), alpha: CGFloat(1.0))
我的自定義類是:
import UIKit
class SPSearchBar: UISearchBar {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit() {
tintColor = Config.purpleColor
barTintColor = Config.scrollBackgroundColor
let cancelButton = value(forKey: "cancelButton") as! UIButton
cancelButton.setTitle(NSLocalizedString("Cancel", comment: ""), for: .normal)
cancelButton.setTitleColor(Config.purpleColor, for: .normal)
cancelButton.tintColor = Config.purpleColor
}
}
看看是否對您有幫助:
let cancelButtonAttributes: NSDictionary = [NSForegroundColorAttributeName: UIColor .red]
UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes as? [String : AnyObject], for: UIControlState.normal)
將這些行添加到您的ViewDidLoad方法中。
嘗試這個:
let cancelButtonSearchButton = searchBar.value(forKeyPath: "cancelButton") as? UIButton
cancelButtonSearchButton?.tintColor = UIColor.blue
這進入ViewController,在其中您設置了UISearchBar的出口
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.