JsW*_*JsW 6 uitextfield uisearchbar ios swift uisearchcontroller
我知道如何设置独立外观,UISearchBar如下所示。
let searchField = searchBar.value(forKey: "searchField") as? UITextField
if let field = searchField {
field.backgroundColor = UIColor.defaultBackgroundColor
field.layer.cornerRadius = 15.0
field.textColor = .white
field.tintColor = .white
field.font = UIFont.systemFont(ofSize: fl(13))
field.layer.masksToBounds = true
field.returnKeyType = .search
}
Run Code Online (Sandbox Code Playgroud)
但这不适用于UISearchController。
我想将占位符和左放大镜图标的文本颜色设置为纯白色。(似乎现在它们上面有一个彩色层)。
另外,输入文本现在是黑色的,我也希望它也是白色的。
最后,我要修改以下属性。
1. textField背景颜色
2. textFiled占位符文本颜色
3. textFiled文本颜色
4. textFiled字体
有人知道怎么做吗?
将以下内容与您的代码添加到viewDidAppear中:
let placeholderString = NSAttributedString(string: "Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
field.attributedPlaceholder = placeholderString
let iconView = field.leftView as! UIImageView
iconView.image = iconView.image?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = .white
Run Code Online (Sandbox Code Playgroud)
Updata:
放入这些设置ViewDidAppear()确实解决了部分问题。
但是,textfield's background color当我设置条形的背景颜色时,更改了。
因为searchBar.barTintColor = .red无法UISearchController在导航项中嵌入的iOS11中工作,所以我经常使它searchBar.backgroundColor = .red
感到困惑。
那么如何分别更改searchBar的背景和textField的背景呢?
attributedPlaceholder为搜索栏的文本字段设置
@IBOutlet weak var sbSearchBar: UISearchBar!
if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {
textfield.backgroundColor = UIColor.red
textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
if let leftView = textfield.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.tintColor = UIColor.white
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
我认为,这可能对您有所帮助:如何在searchcontroller中更改uitextfield颜色?
只需在此代码中应用颜色组合即可查看。
if #available(iOS 11.0, *) {
let sc = UISearchController(searchResultsController: nil)
sc.delegate = self
let scb = sc.searchBar
scb.tintColor = UIColor.white
scb.barTintColor = UIColor.white
if let textfield = scb.value(forKey: "searchField") as? UITextField {
//textfield.textColor = // Set text color
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.white
// Rounded corner
backgroundview.layer.cornerRadius = 10;
backgroundview.clipsToBounds = true;
}
}
if let navigationbar = self.navigationController?.navigationBar {
navigationbar.barTintColor = UIColor.blue
}
navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false
}
Run Code Online (Sandbox Code Playgroud)
结果:

| 归档时间: |
|
| 查看次数: |
6112 次 |
| 最近记录: |