1

I am trying to create an underlined text field with placeholder text, I got the following extension to help out.

extension UITextField {

  func setBottomLine(borderColor: UIColor) {
    
    borderStyle = .none

    backgroundColor = .clear

    let borderLine = CALayer()

    borderLine.frame = CGRect(x: 0, y: frame.height - 2, width: frame.width, height: 2)

    layer.addSublayer(borderLine)

 }

I call this extension in layout subviews of my view controller, and whenever I assign placeholder text nothing shows up. I am very confused on what the problem is. Thanks!

user1046037
  • 16,755
  • 12
  • 92
  • 138
  • why are you calling it it in `layoutSubviews()`, can you try calling it in `viewDidLoad()`? – user1046037 Aug 05 '22 at 02:46
  • The problem I was running into with that is I am using auto layout, so the textField doesn't have a frame during view did load and the underline layer wouldn't add itself correctly Update: I tried removing the call to my extension all together, and the place holder continues not to show @user1046037 – Michael Abrams Aug 05 '22 at 02:54
  • I did this long back, refer https://stackoverflow.com/a/37853543 – user1046037 Aug 05 '22 at 02:59
  • 1
    Oh, I was forgetting to call super.layoutSubviews and it was causing major issues. Also thanks for linking that fourm – Michael Abrams Aug 05 '22 at 04:30

2 Answers2

0
    extension UITextField {
    
        func setUnderLine() {
            let border = CALayer()
            let width = CGFloat(0.5)
            border.borderColor = UIColor.darkGray.cgColor
            border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width - 10, height: self.frame.size.height)
            border.borderWidth = width
            self.layer.addSublayer(border)
            self.layer.masksToBounds = true
        }
    }
override func viewDidLoad() {
            super.viewDidLoad()
            mytextField.setUnderLine()
}
NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51
0

Check this out.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var yourTextField: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    yourTextField.textFieldUnderscoreAndPlaceholder()

    }
}

extension UITextField {

    //MARK: Text underscore with placeholder
    func textFieldUnderscoreAndPlaceholder() {
    
    //Underscore
    let textFieldUnderscore = CALayer()
    textFieldUnderscore.frame = CGRect(x: 0.0, y: frame.height - 1, width: frame.width, height: 1.0)
    bounds = bounds.insetBy(dx: 0, dy: -2)
    textFieldUnderscore.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
    layer.addSublayer(textFieldUnderscore)
    
    //Placeholder
    placeholder = "Type some text here..."
    
    }
}
Gucci
  • 47
  • 1
  • 7