Muhammed Alkabani
Muhammed Alkabani

Reputation: 91

Add bottom border for UISearchBar textField

I have a UISearchBar added to a navigationItem's titleView. I would like to add a bottom border to the UISearchBar's textField.

When try to add a layer, nothing appears.

extension UITextField {

func underlined() {

         let border = CALayer()
         let width = CGFloat(3.0)
         border.borderColor = UIColor.red.cgColor
         border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: width)
         border.borderWidth = width
         self.layer.addSublayer(border)
         self.layer.masksToBounds = true

    }

}

I tried this code to get the content of the textField, but without luck.

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField

textFieldInsideSearchBar?.borderStyle = .none
textFieldInsideSearchBar?.textColor = UIColor.white
textFieldInsideSearchBar?.underlined()

Help would be highly appreciated!

Upvotes: 1

Views: 518

Answers (2)

Ali Moazenzadeh
Ali Moazenzadeh

Reputation: 624

Thats because in viewDidLoad method, frames not configured properly yet, try this:

 override func viewWillAppear(_ animated: Bool) {
    let textFieldInsideSearchBar = searchBar.value(forKey: "_searchField") as? UITextField
    textFieldInsideSearchBar?.borderStyle = .none
    textFieldInsideSearchBar?.textColor = UIColor.white
    textFieldInsideSearchBar?.underlined()
}

Upvotes: 2

JAHID HASAN POLASH
JAHID HASAN POLASH

Reputation: 191

Put the code to read searchbar's textfield and setUnderline in viewDidAppear(:) method instead of viewDidLoad(:).

The problem is you are setting the textField sublayer before its getting its frame. Try printing the frame of the textfield and you will find (0,0,0,0) which leads to the y position of the sublayer to zero. So, set it after the view appears thus it will have its bounds and y position to the desired.

Upvotes: 1

Related Questions