LoginSignup
14
8

More than 5 years have passed since last update.

UITextFieldのテキストの左側に余白を設ける(Swift4)

Posted at

はじめに

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)
    }
14
8
1

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
14
8