textFieldInsideSearchBar

textFieldInsideSearchBar

我在UISearchBar的titleView中添加了navigationItem
我想在UISearchBar的textField中添加底部边框。

尝试添加图层时,没有任何显示。

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

    }

}

我尝试使用此代码来获取textField的内容,但是没有运气。
let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField

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

帮助将不胜感激!

最佳答案

那是因为在viewDidLoad方法中,尚未正确配置框架,请尝试以下操作:

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

10-08 05:04