30

I want to show only bottom border and hide the other sides.

Output I see: As you can see I see the top, left and right borders also and they are black in color, I want to remove them. Only need the bottom white thick 2.0 border.

enter image description here

Code I am using (source):

var border = CALayer()
var width = CGFloat(2.0)
border.borderColor = UIColor.whiteColor().CGColor
border.frame = CGRect(x: 0, y: tv_username.frame.size.height - width, width: tv_username.frame.size.width, height: tv_username.frame.size.height)

border.borderWidth = width
tv_username.backgroundColor = UIColor.clearColor()
tv_username.layer.addSublayer(border)
tv_username.layer.masksToBounds = true
tv_username.textColor = UIColor.whiteColor()
Community
  • 1
  • 1
user1406716
  • 9,565
  • 22
  • 96
  • 151

14 Answers14

72

Try to do by this way, with Swift 5.1:

var bottomLine = CALayer()
bottomLine.frame = CGRect(x: 0.0, y: myTextField.frame.height - 1, width: myTextField.frame.width, height: 1.0)
bottomLine.backgroundColor = UIColor.white.cgColor
myTextField.borderStyle = UITextField.BorderStyle.none
myTextField.layer.addSublayer(bottomLine)

You have to set the borderStyle property to None

If you are using the autolayout then set perfect constraint else bottomline will not appear.

Hope it helps.

thedp
  • 8,350
  • 16
  • 53
  • 95
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
  • tried the code but I see all border disappear with that this code. (my background is blue, not sure if that matters). I want the bottom border to be white only. – user1406716 Jun 29 '15 at 04:58
  • @user1406716 Check this : http://stackoverflow.com/questions/30701655/how-to-get-this-see-inside-type-of-a-uitextfield/30701711#30701711 My answer – Ashish Kakkad Jun 29 '15 at 05:04
  • meaning is there anything additional required other than the 5 lines above? I used them just replacing `myTextField` with my 'tv_username` UITextField – user1406716 Jun 29 '15 at 05:04
  • hmm, strange then because I see only this (no bottom border): http://imgur.com/i2h1zXj – user1406716 Jun 29 '15 at 05:07
  • 1
    I will mark your answer as the answer, but I only had to add **this** line to the code in my question (so may be you want to edit the answer for anyone who reads this later): `myTextField.borderStyle = UITextBorderStyle.None` – user1406716 Jun 29 '15 at 05:10
  • @user1406716 border must be at position : (height **minus** your line height). – Ashish Kakkad Jun 29 '15 at 05:14
  • "If you are using the autolayout then set perfect constraint else bottomline will not appear." -> That is Key. In my sandbox app, I hadn't applied any constraints and I would see bottom border and normal gray rounded edge border when using UITextBorderStyleRoundedRect but not when using UITextBorderStyleNone I would see nothing. Had to set constraints of my UITextField in IB, then it all worked. – Kento Feb 27 '16 at 17:19
  • 3
    what does it mean to set "perfect" constaint? – theDC Jan 12 '17 at 15:29
  • @DCDC little late but "perfect" constraint means set a hard height for the textfield in IB – Sahir Feb 22 '17 at 20:58
  • instead of background color I used border color in order to work – iosMentalist Sep 13 '20 at 18:55
18

Thought from @Ashish's answer, used same approach long ago in Objective-C but implementing extension will be more useful.

extension UITextField {
    func addBottomBorder(){
        let bottomLine = CALayer()
        bottomLine.frame = CGRect(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
        bottomLine.backgroundColor = UIColor.white.cgColor
        borderStyle = .none
        layer.addSublayer(bottomLine)
    }
}

In your controller:

self.textField.addBottomBorder()

Can add further parameters to your method, like adding border height, color.

fredpi
  • 8,414
  • 5
  • 41
  • 61
iBug
  • 2,334
  • 3
  • 32
  • 65
  • 2
    Thanks. It worked for me. Also i could go further: extension UITextField { public func addBottomBorder(color: UIColor = UIColor.black, marginToUp: CGFloat = 1.00, height: CGFloat = 1.00){ let bottomLine = CALayer() bottomLine.frame = CGRect(x: 0, y: self.frame.size.height - marginToUp, width: self.frame.size.width, height: height) bottomLine.backgroundColor = color.cgColor borderStyle = .none layer.addSublayer(bottomLine) } } – Fernando Perez Sep 25 '19 at 15:36
  • Good answer.Thanks iBug. – KSR May 02 '21 at 05:40
7

@mina-fawzy I liked the answer that included masksToBounds by Mina Fawzy...

I ran into this issue where I was trying to style a bottom border of a UITextField, and the comments using a CGRect worked for me, however, I ran into issues when using different screen sizes, or if I changed the orientation to landscape view from the portrait.

ie. My Xcode Main.storyboard was designed with iPhone XS Max, with a UITextField constrained to be 20 points from the left/right of the screen. In my viewDidLoad() I stylized the UITextField (textfield) using the CGRect approach, making the width of the rectangle equal to textfield.frame.width.

When testing on the iPhone XS Max, everything worked perfectly, BUT, when I tested on iPhone 7 (smaller screen width) the CGRect was grabbing the width of the iPhone XS Max during the viewDidLoad(), causing the rectangle (bottom line) to be too wide, and the right edge went off the screen. Similarly, when I tested on iPad screens, the bottom line was way too short. And also, on any device, rotating to landscape view did not re-calculate the size of the rectangle needed for the bottom line.

The best solution I found was to set the width of the CGRect to larger than the longest iPad dimension (I randomly chose 2000) and THEN added textfield.layer.masksToBounds = true. This worked perfectly because now the line is plenty long from the beginning, does not need to be re-calculated ever, and is clipped to the correct width of the UITextField no matter what screen size or orientation.

Thanks Mina, and hope this helps others with the same issue!

Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
Wackerow
  • 71
  • 1
  • 4
  • This is the correct answer + explanation and I wish the accepted answer would incorporate this "gotcha". One improvement I can add is instead of choosing an arbitrary width, you can use the actual device screen width via UIScreen.main.bounds.width (not the width of the textfield like the accepted answer!). – JRam13 Sep 27 '19 at 00:12
6

Objective C

[txt.layer setBackgroundColor: [[UIColor whiteColor] CGColor]];
[txt.layer setBorderColor: [[UIColor grayColor] CGColor]];
[txt.layer setBorderWidth: 0.0];
[txt.layer setCornerRadius:12.0f];
[txt.layer setMasksToBounds:NO];
[txt.layer setShadowRadius:2.0f];
txt.layer.shadowColor = [[UIColor blackColor] CGColor];
txt.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
txt.layer.shadowOpacity = 1.0f;
txt.layer.shadowRadius = 1.0f;

Swift

textField.layer.backgroundColor = UIColor.whiteColor().CGColor
textField.layer.borderColor = UIColor.grayColor().CGColor
textField.layer.borderWidth = 0.0
textField.layer.cornerRadius = 5
textField.layer.masksToBounds = false
textField.layer.shadowRadius = 2.0
textField.layer.shadowColor = UIColor.blackColor().CGColor
textField.layer.shadowOffset = CGSizeMake(1.0, 1.0)
textField.layer.shadowOpacity = 1.0
textField.layer.shadowRadius = 1.0
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
Mitul Marsoniya
  • 5,272
  • 4
  • 33
  • 57
6

I have tried all this answer but no one worked for me except this one

  let borderWidth:CGFloat = 2.0 // what ever border width do you prefer 
    let bottomLine = CALayer()

    bottomLine.frame = CGRectMake(0.0, Et_textfield.height  - borderWidth, Et_textfield.width, Et_textfield.height )
    bottomLine.backgroundColor = UIColor.blueColor().CGColor
    bottomLine
    Et_textfield.layer.addSublayer(bottomLine)
    Et_textfield.layer.masksToBounds = true // the most important line of code
Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
6

Swift 3:

Just subclass your UITextField

class BottomBorderTF: UITextField {

var bottomBorder = UIView()
override func awakeFromNib() {

    //MARK: Setup Bottom-Border
    self.translatesAutoresizingMaskIntoConstraints = false
    bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    bottomBorder.backgroundColor = UIColor.orange
    bottomBorder.translatesAutoresizingMaskIntoConstraints = false
    addSubview(bottomBorder)
    //Mark: Setup Anchors
    bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    bottomBorder.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
    bottomBorder.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
    bottomBorder.heightAnchor.constraint(equalToConstant: 1).isActive = true // Set Border-Strength

   }
}
Codetard
  • 2,441
  • 28
  • 34
3

Solution which using CALayer is not good because when device is rotated the underline doesn't change width.

class UnderlinedTextField: UITextField {

    override func awakeFromNib() {
        super.awakeFromNib()

        let bottomLine = CALayer()
        bottomLine.frame = CGRect(x: 0, y: self.frame.size.height, width: UIScreen.main.bounds.width, height: 1)
        bottomLine.bounds = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: self.frame.size.height)
        bottomLine.backgroundColor = UIColor.black.cgColor
        borderStyle = .none
        layer.addSublayer(bottomLine)
        layer.masksToBounds = true
    }
}

The best solution is to use UIView.

class UnderlinedTextField: UITextField {
    private let defaultUnderlineColor = UIColor.black
    private let bottomLine = UIView()

    override func awakeFromNib() {
        super.awakeFromNib()

        borderStyle = .none
        bottomLine.translatesAutoresizingMaskIntoConstraints = false
        bottomLine.backgroundColor = defaultUnderlineColor

        self.addSubview(bottomLine)
        bottomLine.topAnchor.constraint(equalTo: self.bottomAnchor, constant: 1).isActive = true
        bottomLine.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        bottomLine.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        bottomLine.heightAnchor.constraint(equalToConstant: 1).isActive = true
    }

    public func setUnderlineColor(color: UIColor = .red) {
        bottomLine.backgroundColor = color
    }

    public func setDefaultUnderlineColor() {
        bottomLine.backgroundColor = defaultUnderlineColor
    }
}
DavidB.
  • 99
  • 1
  • 4
Vitaliy
  • 25
  • 3
3

First set borderStyle property to .none.

Also, don't forget that the best time to call this method in the viewDidAppear(_:) method.

To make it handy, you can use an extension:

extension UIView {
    func addBottomBorderWithColor(color: UIColor, width: CGFloat) {
        let border = CALayer()
        border.backgroundColor = color.cgColor
        border.frame = CGRect(x: 0, y: self.frame.size.height - width, 
                              width: self.frame.size.width, height: width)
        self.layer.addSublayer(border)
    }
}

Call it like:

textfield.addBottomBorderWithColor(color: UIColor.lightGray, width: 0.5)
meow2x
  • 2,056
  • 22
  • 27
3

Using extension and Swift 5.3

extension UITextField {
    internal func addBottomBorder(height: CGFloat = 1.0, color: UIColor = .black) {
        let borderView = UIView()
        borderView.backgroundColor = color
        borderView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(borderView)
        NSLayoutConstraint.activate(
            [
                borderView.leadingAnchor.constraint(equalTo: leadingAnchor),
                borderView.trailingAnchor.constraint(equalTo: trailingAnchor),
                borderView.bottomAnchor.constraint(equalTo: bottomAnchor),
                borderView.heightAnchor.constraint(equalToConstant: height)
            ]
        )
    }
}
rami
  • 129
  • 2
  • 10
  • This was the better solution for me since I needed to hide/show the `TextField` and could not use frame and CALayer as I had to do it in `viewDidLoad`. – rule_it_subir Nov 05 '21 at 06:14
1

For those looking for a solution that works for Autolayout, IBInspectable, and the Storyboard, subclass UITextField into your custom textfield class and add these:

func setUnderline() {
    for sub in self.subviews {
        sub.removeFromSuperview()
    }
    if underlineStyle == true {
        var bottomBorder = UIView()
        bottomBorder = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        bottomBorder.backgroundColor = borderColor  //YOUR UNDERLINE COLOR HERE
        bottomBorder.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(bottomBorder)

        bottomBorder.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
        bottomBorder.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        bottomBorder.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        bottomBorder.heightAnchor.constraint(equalToConstant: underlineHeight).isActive = true
        layoutIfNeeded()
    }
}

@IBInspectable var underlineStyle: Bool = false {
    didSet {
       setUnderline()
    }
}

@IBInspectable var underlineHeight: CGFloat = 0 {
    didSet {
        setUnderline()
    }
}
smakus
  • 1,107
  • 10
  • 11
  • 1
    This. I tried almost every other method here and none worked well with my hybrid auto-layout methods until this :) – mpc75 May 12 '20 at 01:01
1

Swift 5.

extension UITextField {
    let bottomLine = UIView()
    bottomLine.backgroundColor = .black
    borderStyle = .none
        
    self.addSubview(bottomLine)

    NSLayoutConstraint.activate([
        bottomLine.topAnchor.constraint(equalTo: bottomAnchor + 10),
        bottomLine.leadingAnchor.constraint(equalTo: leadingAnchor),
        bottomLine.trailingAnchor.constraint(equalTo: trailingAnchor),
        bottomLine.heightAnchor.constraint(equalToConstant: 1)
    ]) 
}
andrewlundy
  • 1,073
  • 15
  • 22
0

For multiple Text Field

  override func viewDidLoad() {


    configureTextField(x: 0, y: locationField.frame.size.height-1.0, width: locationField.frame.size.width, height:1.0, textField: locationField)
    configureTextField(x: 0, y: destinationField.frame.size.height-1.0, width: destinationField.frame.size.width, height:1.0, textField: destinationField)
    configureTextField(x: 0, y: originField.frame.size.height-1.0, width: originField.frame.size.width, height:1.0, textField: originField)
    configureTextField(x: 0, y: nameField.frame.size.height-1.0, width: nameField.frame.size.width, height:1.0, textField: nameField)

    locationField.text="Hello"
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

func configureTextField(x:CGFloat,y:CGFloat,width:CGFloat,height:CGFloat,textField:UITextField)

{
    let bottomLine = CALayer()
    bottomLine.frame = CGRect(x: x, y: y, width: width, height: height)
    bottomLine.backgroundColor = UIColor.white.cgColor
    textField.borderStyle = UITextBorderStyle.none
    textField.layer.addSublayer(bottomLine)


}
garg
  • 2,651
  • 1
  • 24
  • 21
0

Textfield bottom border set but some more issues for devices.So bottom border not fit in textfield.I retrieve that problem the code like this It works fine swift 4.2

let bottomLine = CALayer()
        bottomLine.frame = CGRect(x: 0.0, y: textField.frame.height - 1, width: screenSize.width - 32, height: 1.0)
        bottomLine.backgroundColor = UIColor(hex: 0xD5D5D5).cgColor
        textField.borderStyle = UITextField.BorderStyle.none
        textField.layer.addSublayer(bottomLine)
Srinivasan_iOS
  • 972
  • 10
  • 12
0

For swift 4. this works for me.

   let myfield:UITextField = {
        let mf=UITextField()
        let atributePlaceHolder=NSAttributedString(string: "Text_description", attributes:[NSAttributedString.Key.foregroundColor :UIColor.darkGray])
        mf.textColor = .gray
        mf.attributedPlaceholder=atributePlaceHolder
        mf.layer.borderColor = UIColor.black.cgColor
        mf.layer.backgroundColor = UIColor.white.cgColor
        mf.layer.borderWidth = 0.0
        mf.layer.shadowOffset = CGSize(width: 0, height: 1.0)
        mf.layer.shadowOpacity = 1.0
        mf.layer.shadowRadius = 0.0
        return mf
    }()
Santi
  • 1
  • 1