How to put a padding into a UITextField ?

In iOS development you can put a padding into a UITextField with a code below.

First of all , you can create a customized UITextField class for giving it an inset . And then you can put a code below into the class inherited UITextField class.

let padding = UIEdgeInsets(top: 7, left: 0, bottom: 7, right: 0)

override func textRectForBounds(bounds: CGRect) -> CGRect {
    return UIEdgeInsetsInsetRect(bounds, padding)
}
override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
    return UIEdgeInsetsInsetRect(bounds, padding)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
    return UIEdgeInsetsInsetRect(bounds, padding)
}

UIEdgeInsets Type

UIEdgeInsets is defining a inset distnaces for views. You can easily customize your insets for a view with this type. Positive values will shrink the view and negative value will expand the view.

UIEdgeInsetsInsetRect Function

UIEdgeInsetsInsetRect adjusts a rectangle by the given edge insets. In this code you can adjust a rectangle for textfield’s text and etc with UIEdgeInsetsInsetRect. It receives UIEdgeInsets structure type as a parameter.

I hope that Apple provides a function or an interface that we can easily adjut insets through the interface builder.

Leave a Reply