UITextField Single Line

Hi

I watched this (Create a Single Line Text Field (UITextField) in One Minute - YouTube) tutorial on how to create a single line textfield by adding a calayer. Does anyone know if there’s a problem with this since Iphone 12? When i try this on Iphone 11 simulator it works but when testing on 12 and 13 the line shows greater than the textfield frame.

/ Johan

I just tried that exercise. It works fine on iPhone 11, 12 Pro Max and 13 Pro Max but the line extends to the right on the iPhone 13 mini, iPhone 12 and iPhone 13. I didn’t test it on any others.

It’s a bug I would say.

1 Like

It also worked on my end.

Here’s the code for your reference @johankarlstromer

import UIKit

class ViewController: UIViewController {

  @IBOutlet weak var textField: UITextField!
  
  private let bottomLine = CALayer()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    bottomLine.frame = CGRect(x: 0,
                              y: textField.frame.height - 2,
                              width: textField.frame.width,
                              height: 2)
    
    bottomLine.backgroundColor = UIColor.red.cgColor
    
    textField.borderStyle = .none
    
    textField.layer.addSublayer(bottomLine)
    
  }
}

Hey Joash,

The misalignment shows up on some devices when you set width constraints on the TextField of say 50 leading and 50 trailing rather than taking the textfield right to the edge.

You can also use auto-layout as an alternative


import UIKit

class ViewController: UIViewController {
  
  @IBOutlet weak var textField: UITextField!
  
  let bottomLine: UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = .red
    return view
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    textField.borderStyle = .none
    
    bottomLineViewSetup()
  }
  
  func bottomLineViewSetup() {
    view.addSubview(bottomLine)
    NSLayoutConstraint.activate([
      bottomLine.leadingAnchor.constraint(equalTo: textField.leadingAnchor),
      bottomLine.trailingAnchor.constraint(equalTo: textField.trailingAnchor),
      bottomLine.topAnchor.constraint(equalTo: textField.bottomAnchor),
      bottomLine.heightAnchor.constraint(equalToConstant: 2.0)
    ])
  }
}

To learn more about auto-layout you can check this link

and if you want to go further about building an app programmatically you can also check this article

2 Likes

Thanks. I’ll try this.

This works well on all devices. Great solution Joash.

1 Like