Scott Perry Scott Perry - 2 months ago 17
Swift Question

iOS UITextField Border Style in swift

UI Interface Login example

I've added this image, I hope you can see it, of a user interface login. Notice the text field is transparent with the exception of the line at the bottom. What code do I put in to get that affect? Can I put the necessary information in the "user defined runtime attributes"?

Answer

Your output

Create custom class(Sub class of UITextField) as below, And simply set this class in your storyboard to UItextField

  import Foundation
  import UIKit

    class UITextField_BottomBorder: UITextField , UITextFieldDelegate {

        let border = CALayer()
        let width = CGFloat(2.0)

        required init?(coder aDecoder: (NSCoder!)) {
            super.init(coder: aDecoder)               
            self.delegate=self;
            border.borderColor = UIColor( red: 32.0/255, green: 53.0/255, blue:88.0/255, alpha: 1.0 ).CGColor

            border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)
            border.borderWidth = width
            self.layer.addSublayer(border)
            self.layer.masksToBounds = true
        }

        override func drawRect(rect: CGRect) {
            border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)
        }

        override func awakeFromNib() {
            super.awakeFromNib()                
            border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)       
        }
  }