简体   繁体   English

为UISearchBar textField添加底部边框

[英]Add bottom border for UISearchBar textField

I have a UISearchBar added to a navigationItem 's titleView. 我有一个UISearchBar添加到navigationItem的titleView。 I would like to add a bottom border to the UISearchBar 's textField. 我想在UISearchBar的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. 我尝试使用此代码来获取textField的内容,但没有运气。

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

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

Help would be highly appreciated! 帮助将非常感谢!

Thats because in viewDidLoad method, frames not configured properly yet, try this: 那是因为在viewDidLoad方法中,帧还没有正确配置,试试这个:

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

Put the code to read searchbar's textfield and setUnderline in viewDidAppear(:) method instead of viewDidLoad(:). 将代码放在viewDidAppear(:)方法而不是viewDidLoad(:)中读取searchbar的textfield和setUnderline。

The problem is you are setting the textField sublayer before its getting its frame. 问题是你在设置textField子图层之前设置它。 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. 尝试打印文本框的框架,你会发现(0,0,0,0)导致子图层的y位置为零。 So, set it after the view appears thus it will have its bounds and y position to the desired. 因此,在视图出现后设置它,因此它将具有所需的边界和y位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM