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.

Zrzut ekranu 2017-01-12 o 20.26.05

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

 

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 calculation

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

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

 

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

Thanks for reading!