How to Left-Align Text in a UIButton

How to Left-Align Text in a UIButton

28 February 2025 Stephan Petzl Leave a comment Xcode

When designing user interfaces, aligning text within UI components such as buttons is essential for maintaining a cohesive and professional appearance. In this article, we will explore how to left-align text within a UIButton in iOS, using both Swift and Objective-C. This guide is especially useful for developers who want to display information, such as an email address, neatly aligned on the left side of a button.

Solution: Using contentHorizontalAlignment

One effective approach to left-aligning text in a UIButton is by setting the contentHorizontalAlignment property. This method is straightforward and can be implemented in both Swift and Objective-C.

Swift

emailBtn.contentHorizontalAlignment = .left

Objective-C

emailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

To prevent the text from touching the button’s left edge, it is advisable to adjust the content insets. This provides a buffer around the text, enhancing readability and visual appeal.

Adjusting Content Insets

Swift

emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);

Objective-C

emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);

Alternative: Interface Builder

For developers who prefer a visual approach, Interface Builder offers a user-friendly way to adjust button properties without writing code. Users can set the text alignment and adjust insets directly within the Interface Builder’s properties panel.

Advanced Considerations

If you are working with complex layouts or require additional customization, consider using UIButton’s configuration APIs introduced in iOS 15+. These APIs allow for more nuanced control over button appearance and behavior, although they may require additional setup.

Enhancing Test Automation with Repeato

As you refine your app’s UI, ensuring consistent behavior across different devices and scenarios becomes crucial. This is where Repeato, a no-code test automation tool, can be invaluable. Repeato allows you to create and maintain automated tests for iOS apps quickly and efficiently. With features like data-driven and keyword-driven testing, Repeato helps streamline your testing process, ensuring that UI components like buttons behave as expected across various conditions. For more information on how Repeato can enhance your testing strategy, visit our documentation page.

Like this article? there’s more where that came from!