How to change UISearchBar Placeholder and image tint color?

前端 未结 12 2381
暖寄归人
暖寄归人 2020-11-29 01:24

I\'ve been trying search results for hours, but I can\'t get this figured out. Perhaps it isn\'t possible. I\'m trying to change the tint color of the placeholder text and m

12条回答
  •  甜味超标
    2020-11-29 02:08

    I made a Swift 4.1 search bar extension:

    import Foundation
    import UIKit
    extension UISearchBar{
        func setTextField(placeHolderColor:UIColor = .gray,placeHolder:String = "Search Something",textColor:UIColor = .white,backgroundColor:UIColor = .black,
                          placeHolderFont:UIFont = UIFont.systemFont(ofSize: 12.0),
                          textFont:UIFont =  UIFont.systemFont(ofSize: 12.0) ){
            for item in self.subviews{
                for mainView in (item as UIView).subviews{
                    mainView.backgroundColor = backgroundColor
                    if mainView is UITextField{
                        let textField = mainView as? UITextField
                        if let _textF = textField{
                            _textF.text = "success"
                            _textF.textColor = textColor
                            _textF.font      = textFont
                            _textF.attributedPlaceholder = NSMutableAttributedString.init(string: placeHolder, attributes: [NSAttributedStringKey.foregroundColor : placeHolderColor,
                                                                                                                                   NSAttributedStringKey.font : placeHolderFont])
                        }
                    }
                }
            }
        }
    }
    

    You can use this for your searchBar like this :

    controller.searchBar.setTextField(placeHolderColor: .white,
     placeHolder: "Search A Pet",
     textColor: .white,
     backgroundColor: .green,
     placeHolderFont: UIFont.systemFont(ofSize: 14.0),
     textFont: UIFont.systemFont(ofSize: 14.0))
    

提交回复
热议问题