Search code examples
swift2ios9

Text Field with Only top and Bottom Border using swift 2


I have a page for forgot password. It has only a text field asking the user to fill in their email address. The Designer designed the text field with top and bottom border only. I tried answer from here UITextField Only Top And Bottom Border but in the result it only shows bottom border for the text field. enter image description here

Like in the image i would like to create a grey border for top and bottom


Solution

  • Thanks @El Captain for the valuable comment and nice answer by @Bjorn Ro even if it was in Objective-c i think. And my answer for the question is (i'm using swift 2 Xcode 7)

    Override the function viewDidLayoutSubviews() in your swift file. And the Code for the same is

    override func viewDidLayoutSubviews() {
    // Creates the bottom border
            let borderBottom = CALayer()
            let borderWidth = CGFloat(2.0)
            borderBottom.borderColor = UIColor.grayColor().CGColor
            borderBottom.frame = CGRect(x: 0, y: forgotPasswordEmailText.frame.height - 1.0, width: forgotPasswordEmailText.frame.width , height: forgotPasswordEmailText.frame.height - 1.0)
            borderBottom.borderWidth = borderWidth
            forgotPasswordEmailText.layer.addSublayer(borderBottom)
            forgotPasswordEmailText.layer.masksToBounds = true
    
    // Creates the Top border
            let borderTop = CALayer()
            borderTop.borderColor = UIColor.grayColor().CGColor
            borderTop.frame = CGRect(x: 0, y: 0, width: forgotPasswordEmailText.frame.width, height: 1)
            borderTop.borderWidth = borderWidth
            forgotPasswordEmailText.layer.addSublayer(borderTop)
            forgotPasswordEmailText.layer.masksToBounds = true
    
        }
    

    forgotPasswordEmailText is the text field for entering Email

    The Final output looks like this... with a gray Colour border (Screen shot of iPhone 4s Simulator)enter image description here