はじめに
Obj-C時代から思っていましたが、UITextViewにはテキストの左側に余白があるのに、なぜUITextFieldにはないのでしょうか…。
ということで、こちらの記事を参考にさせていただき、Swift4でUITextFieldのテキストの左側にパディング(内側の余白)を実装します。
パディングの実装
@IBInspectable
を使うことにより、ストーリーボード上で padding
の値を指定できるようにしています。
デフォルト値を設定しているため、値を指定しなくても使えます。
PaddingTextField.swift
import UIKit
@IBDesignable class PaddingTextField: UITextField {
// MARK: Properties
/// テキストの内側の余白
@IBInspectable var padding: CGPoint = CGPoint(x: 6.0, y: 0.0)
// MARK: Internal Methods
override func textRect(forBounds bounds: CGRect) -> CGRect {
// テキストの内側に余白を設ける
return bounds.insetBy(dx: self.padding.x, dy: self.padding.y)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
// 入力中のテキストの内側に余白を設ける
return bounds.insetBy(dx: self.padding.x, dy: self.padding.y)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
// プレースホルダーの内側に余白を設ける
return bounds.insetBy(dx: self.padding.x, dy: self.padding.y)
}