LoginSignup
35
27

More than 5 years have passed since last update.

【Swift3】UITextFiledのborderを下線のみにする方法

Last updated at Posted at 2016-10-17

デモ

これを
スクリーンショット 2016-10-18 8.37.34.png

こうする
スクリーンショット 2016-10-18 8.38.03.png

準備

StoryboardでUITextfieldを配置、Border Styleを一番左のNo Borderにしておく。
borderbottom.png

方法1

ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

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

        border.borderColor = UIColor.gray.cgColor
        border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width:  textField.frame.size.width, height: 1)
        border.borderWidth = width

        textField.placeholder = "NAME"
        textField.layer.addSublayer(border)
    }
}

この方法だと複数のUITextFieldを変更する場合コードが長くなる。
その場合は次のextensionを使う。

方法2

ViewController.swift
import UIKit

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

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.placeholder = "NAME"
        textField.addBorderBottom(height: 1.0, color: UIColor.lightGray)
    }
}

参考

UITextField border for bottom side only in swift
UITextFieldに下線を追加

35
27
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
35
27