Swift 3: Custom UITextField with single line input

Hi everyone!

This is going to be a short tips&tricks style article.

Today I was trying (and suceed fortunately) to built a custom UITextField that consists of one bottom line. I’m sure you have seen it before, or at least *something* like this.

It’s not much complicated, but things gets tricky when using autolayout. Let’s have a look how to make such UITextField first, all you need to do is create extension

extension UITextField {
  func setBottomLine(borderColor: UIColor) {
   self.borderStyle = UITextBorderStyle.none
   self.backgroundColor = UIColor.clear
   let borderLine = UIView()
   borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) —    height, width: Double(self.frame.width), height: height)
   borderLine.backgroundColor = borderColor
   self.addSubview(borderLine)
   }
}

You might wonder what the heck is going on up there, I will explan right away!

After we set transparent background and disable borders for the textfield, UIView is created.
 Then we set its frame to the line of height equal to 1.0 and place it at the bottom of textfield by the following y point calculation

Double(self.frame.height) — height

What comes next is setting background color and subview is ready to be added. Pretty neat!

Now, the tricky part for those who want to use autolayout:

Don’t you dare to call

setBottomLine(borderColor: UIColor)

in ViewDidLoad(), it leads to undetermined behaviour since not all autolayout rules have been applied at that time.

To get it correct, just call the method inside viewDidLayoutSubviews() function

override func viewDidLayoutSubviews() {
  let lineColor = UIColor(red:0.12, green:0.23, blue:0.35, alpha:1.0)
  self.myTextField.setBottomBorder(borderColor: lineColor)
}

That’s it! Let me know if it works for you!


Originally published at codepany.com on January 12, 2017.