无法在UISearchController中为UITextField设置正确的背景颜色

时间:2018-09-17 08:20:07

标签: ios swift xcode

我在我的项目中使用UISearchController就像这里https://www.youtube.com/watch?v=h7caxpp3Xps 我尝试设置textField背景,像在这里的答案: iOS 11 customise search bar in navigation bar 如果我使用蓝色,绿色,白色,黑色等颜色都可以 但是当我尝试设置另一种颜色时,得到的结果是

enter image description here

另外,我在UISearchBarTextField中有两个_UISearchBarSearchFieldBackgroundView,其中一个由另一种颜色填充 enter image description here

这是苹果开发人员的错误吗?

viewController的代码-enter link description here

3 个答案:

答案 0 :(得分:0)

在UIColor扩展中创建类属性

extension UIColor
{
  class var themeColor:UIColor {
    return UIColor(red: 210.0/255.0, green: 105.0/255.0, blue: 130.0/255.0, alpha: 1.0)
  }
}
OR

extension UIColor {
  static let themeColor = UIColor(red: 210.0/255.0, green: 105.0/255.0, blue: 130.0/255.0, alpha: 1.0)
}
Usage

self.view.backgroundColor = UIColor.themeColor

原始答案here

答案 1 :(得分:0)

您可以设置searchBar的颜色和背景色。

controller.searchBar.barTintColor = UIColor.appThemeColor() controller.searchBar.backgroundColor = UIColor.white

controller.searchBar.tintColor = Color.theme.value

答案 2 :(得分:0)

如果需要,还可以尝试使用此代码自定义其他内容

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.searchBar.customize()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension UISearchBar {
    func customize(){
        self.backgroundColor = UIColor.clear
        self.backgroundImage = UIImage()

        for subView in self.subviews  {
            for subsubView in subView.subviews  {
                if let textField = subsubView as? UITextField {
                    textField.clearButtonMode = .whileEditing
                    textField.backgroundColor = UIColor.red
                    textField.layer.cornerRadius = textField.bounds.size.height / 2
                    textField.layer.masksToBounds = true
                    textField.layer.borderColor = UIColor.black.cgColor
                    textField.layer.borderWidth = 1.0
                }
            }
        }

        self.setImage(UIImage(named: "searchfield")?.withRenderingMode(.alwaysTemplate), for: UISearchBarIcon.search, state: .normal)
        self.setPositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: UISearchBarIcon.search)
        self.searchTextPositionAdjustment = UIOffset(horizontal: 8, vertical: 0)
    }
}