3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UITextFieldに下線を引く(縦向き、横向き切替対応)

Posted at

TextFieldに下線を引く方法はググると直ぐ出てきて、draw(_:)に記述すれば対応出来ます。
ただ、これで行うとPortrait (縦向き) モードからLandscape (横向き) モードにしても下線が短いままです。
(TextFieldをAutoLayoutで画面の横幅一杯にしている場合など)
ちなみに、フォーカスすると再度draw(_:)が呼び出されるので下線が横幅一杯になります。

Portrait (縦向き) モードと Landscape (横向き) モードでの切替に対応するには切り替えた事を検知して横幅を変更してあげればいいのでプロパティ監視の機能を使ってboundsが変更されたときにborderを更新するようにすると上手くいきます。

CustomTextField.swift

import UIKit

class CustomTextField: UITextField {
    override open var bounds: CGRect {
        didSet {
            updateBorder()
        }
    }
    
    private let borderLayer = CALayer()

    override func draw(_ rect: CGRect) {
        updateBorder()
        self.layer.addSublayer(borderLayer)
    }
    
    func updateBorder () {
        borderLayer.backgroundColor = UIColor.borderColor.cgColor
        borderLayer.frame = CGRect(x: 0, y: self.frame.height, width: self.frame.width, height: 0.5)
    }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?