UISearchBar change placeholder color

前端 未结 17 2442
南旧
南旧 2020-12-04 15:16

Has anyone any idea or code sample on how can I change the text color of the placeholder text of a UISearchBar?

17条回答
  •  半阙折子戏
    2020-12-04 15:50

    Try this and see: (I tested below code with Swift 4.1 - Xcode 9.3-beta4)

    @IBOutlet weak var sbSearchBar: UISearchBar!
    
    if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {
    
        textfield.backgroundColor = UIColor.yellow
        textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
    
        textfield.textColor = UIColor.green
    
        if let leftView = textfield.leftView as? UIImageView {
            leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
            leftView.tintColor = UIColor.red
        }
    }
    

    Here is result:

提交回复
热议问题