Irohabook
0
1290

SwiftのUITextFieldに余白(padding)をつける

デフォルトのUITextFieldは、中の文字が隙間なく埋められて見にくい感じになる。枠線と文字の間に余白をつけるには、UITextFieldを継承したクラスを作る。

class CustomTextField: UITextField {

    private let padding: CGFloat = 8

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(padding, padding, padding, padding))
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(padding, padding, padding, padding))
    }

    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(padding, padding, padding, padding))
    }
}

CustomTextFieldのインスタンスはUITextFieldのそれと同じように、ボーダーの太さを変えたり、制約を足したりできる。

textRect、editingRect、placeholderRectの3つを設定する。UITextFieldには文字、編集、プレースホルダーの状態があるため。

次の記事

UIView