UITextField rightView Padding With Swift

In the Swift app I’m developing, I needed a UITextField with a UIPickerView as the inputView, and a down triangle at the right of the UITextField to make it look like a “ComboBox” (from my Java background).

You can add a UIImageView as the rightView of a UITextField, however it doesn’t display very elegantly and actually touches the right edge. Here is what it looks like, keeping in mind that this app has a fun and lively font:

Screen Shot 2015-07-10 at 10.42.33 AM

The rightView is displayed within a rectangle based on the rightViewRectForBounds method, so to correct this anomaly there is a simple fix which is to override the rightViewRectForBounds method in a subclass of UITextField.

Here is the class I defined:

This moves the image over a little to the left so that it doesn’t touch the right edge. This works because the X position of the rightView rectangle is set to less than what it is by default. You might need to adjust the X and Y offset a little depending on your image and how you would like it to be displayed.

The result for my custom down image (created with Sketch 3.x) with a height and width of 18 is below:

Screen Shot 2015-07-10 at 10.20.53 AM

I’m pleased with the result, and I hope this helps someone else facing the same scenario.

Leave a Comment: