Refactored UIButton with Deprecated titleEdgeInsets and imageEdgeInsets

Sometimes, when we increase the iOS version of our application, for example, from iOS 15 to iOS 16, or when Apple releases new Swift APIs and deprecates existing ones, we see a yellow deprecated line in Xcode. This line indicates that some code or API has been deprecated and is no longer recommended for use. Xcode will also suggest an alternative for it. One of our weekly tasks as developers includes updating this deprecated code to the latest version, and this is sometimes an opportunity to learn new Swift APIs.

I recently updated an iOS project from iOS 14 to iOS 15 to take advantage of Apple's new API. I have a custom button with a title and image, and I modified their horizontal positioning using titleEdgeInsets and imageEdgeInsets, which are of type UIEdgeInsets accordingly.

In iOS 15, Apple deprecated titleEdgeInsets and imageEdgeInsets in favour of UIButton.Configuration. This change prompted me to refactor the UIButton to use the iOS 15 UIButton.Configuration.

Image using Deprecated Title and Image Insets

Button with Deprecated TitleEdgeInsets and ImageEdgeInsets

UIButton.Configuration

UIButton.Configuration can be used to configure button properties such as title, subtitle, and image. it can also be utilized to configure the button's appearance, including font, foreground color, the distance between the image and the title (image padding), background, etc. I recommend reading this article by Sarun for a comprehensive read on UIButton.Configuration.

I found the UIButton.Configuration API easier to use and it produces a neater button. By default, the image is positioned behind the title horizontally. I was able to bring it to the front by setting the configuration's image placement to trailing. Additionally, I control the distance between the image and the title using image padding, which is a cleaner approach compared to using imageEdgeInsets—a somewhat hacky implementation.

Another property I found interesting is cornerStyle, which can be used to set the corner radius in place of .layer.cornerRadius. You don't specify an exact floating unit with cornerStyle; instead, you can choose from predefined styles. In my case, I use 'dynamic,' which gives the button some nice, subtle curved edges. If you still want to set the unit, you can use background.cornerRadius, for example.

configuration.background.cornerRadius = 16

Additional customisation can be applied to the button title using the attributeTitle property and the AttributeContainer struct, which includes properties such as font.

Here is the code for the new Button using UIButton.Configuration

New Button with UIButton.Configuartion

Button with UIButton.Configuration

Thank you for reading.