Class

UIButton

A UIButton object is a view that executes your custom code in response to user interactions.

Overview

When you tap a button, or select a button that has focus, the button performs any actions attached to it. You communicate the purpose of a button using a text label, an image, or both. The appearance of buttons is configurable, so you can tint buttons or format titles to match the design of your app. You can add buttons to your interface programmatically or using Interface Builder.

When adding a button to your interface, perform the following steps:

  • Set the type of the button at creation time.

  • Supply a title string or image; size the button appropriately for your content.

  • Connect one or more action methods to the button.

  • Set up Auto Layout rules to govern the size and position of the button in your interface.

  • Provide accessibility information and localized strings.

For information about basic view behaviors, see View Programming Guide for iOS.

Responding to Button Taps

Buttons use the Target-Action design pattern to notify your app when the user taps the button. Rather than handle touch events directly, you assign action methods to the button and designate which events trigger calls to your methods. At runtime, the button handles all incoming touch events and calls your methods in response.

You connect a button to your action method using the addTarget(_:action:for:) method or by creating a connection in Interface Builder. The signature of an action method takes one of three forms, which are listed in Listing 1. Choose the form that provides the information that you need to respond to the button tap.

Listing 1

Action methods for buttons

@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)

Configuring a Button’s Appearance

A button’s type defines its basic appearance and behavior. You specify the type of a button at creation time using the init(type:) method or in your storyboard file. After creating a button, you cannot change its type. The most commonly used button types are the Custom and System types, but use the other types when appropriate.

Button States

Buttons have five states that define their appearance: default, highlighted, focused, selected, and disabled. When you add a button to your interface, it is in the default state initially, which means the button is enabled and the user is not interacting with it. As the user interacts with the button, its state changes to the other values. For example, when the user taps a button with a title, the button moves to the highlighted state.

When configuring a button either programmatically or in Interface Builder, you specify attributes for each state separately. In Interface Builder, use the State Config control in the Attributes inspector to choose the appropriate state and then configure the other attributes. If you do not specify attributes for a particular state, the UIButton class provides a reasonable default behavior. For example, a disabled button is normally dimmed and does not display a highlight when tapped. Other properties of this class, such as the adjustsImageWhenHighlighted and adjustsImageWhenDisabled properties, let you alter the default behavior in specific cases.

Content

The content of a button consists of a title string or image that you specify. The content you specify is used to configure the UILabel and UIImageView object managed by the button itself. You can access these objects using the titleLabel or imageView properties and modify their values directly. The methods of this class also provide a convenient shortcut for configuring the appearance of your string or image.

Normally, you configure a button using either a title or an image and size the button accordingly. Buttons can also have a background image, which is positioned behind the content you specify. It is possible to specify both an image and a title for buttons, which results in the appearance shown in Figure 1. You can access the current content of a button using the indicated properties.

Figure 1

Providing a title and image for a button

When setting the content of a button, you must specify the title, image, and appearance attributes for each state separately. If you do not customize the content for a particular state, the button uses the values associated with the Default state and adds any appropriate customizations. For example, in the highlighted state, an image-based button draws a highlight on top of the default image if no custom image is provided.

Tint Color

You can specify a custom button tint using the tintColor property. This property sets the color of the button image and text. If you do not explicitly set a tint color, the button uses its superview’s tint color.

Edge Insets

Use insets to add or remove space around the content in your custom or system buttons. You can specify separate insets for your button’s title (titleEdgeInsets), image (imageEdgeInsets), and both the title and image together (contentEdgeInsets). When applied, insets affect the corresponding content rectangle of the button, which is used by the Auto Layout engine to determine the button’s position.

There should be no reason for you to adjust the edge insets for info, contact, or disclosure buttons.

Interface Builder Attributes

Table 1 lists the core attributes that you configure for buttons in Interface Builder.

Table 1

Core attributes

Attribute

Description

Type

The button type. This attribute determines the default settings for many other button attributes. The value of this attribute cannot be changed at runtime, but you can access it using the buttonType property.

State Config

The state selector. After selecting a value in this control, changes to the button’s attributes apply to the specified state.

Title

The button’s title. You can specify a button’s title as a plain string or attributed string.

(Title Font and Attributes)

The font and other attributes to apply to the button’s title string. The specific configuration options depends on whether you specified a plain string or attributed string for the button’s title. For a plain string, you can customize the font, text color, and shadow color. For an attributed string, you can specify alignment, text direction, indentation, hyphenation, and many other options.

Image

The button’s foreground image. Typically, you use template images for a button’s foreground, but you may specify any image in your Xcode project.

Background

The button’s background image. The background image is displayed behind its title and foreground image.

Table 2 lists attributes that affect the button’s appearance.

Table 2

Appearance attributes

Attribute

Description

Shadow Offset

The offsets and behavior of the button’s shadow. Shadows affect title strings only. Enable the Reverses on Highlight option to change the highlighting of the shadow when the button state changes to or from the highlighted state.

Configure the offsets programmatically using the shadowOffset property of the button’s titleLabel object. Configure the highlighting behavior using the reversesTitleShadowWhenHighlighted property.

Drawing

The drawing behavior of the button.

When the Shows Touch On Highlight (showsTouchWhenHighlighted) option is enabled, the button adds a white glow to the part of a button that the user touches.

When the Highlighted Adjusts Image (adjustsImageWhenHighlighted) option is enabled, button images get darker when it is in the highlighted state.

When the Disabled Adjusts Image (adjustsImageWhenDisabled) option is enabled, the image is dimmed when the button is disabled.

Line Break

The line breaking options for the button’s text. Use this attribute to define how the button’s title is modified to fit the available space.

Table 3 lists the edge inset attributes for buttons. Use edge inset buttons to alter the rectangle for the button’s content.

Table 3

Edge inset attributes

Attribute

Description

Edge

The edge insets to configure. You can specify separate edge insets for the button’s overall content, its title, and its image.

Inset

The inset values. Positive values shrink the corresponding edge, moving it closer to the center of the button. Negative values expand the edge, moving it away from the center of the button. Access these values at runtime using the contentEdgeInsets, titleEdgeInsets, and imageEdgeInsets properties.

For information about the button’s inherited Interface Builder attributes, see UIControl and UIView.

Internationalization

To internationalize a button, specify a localized string for the button’s title text. (You may also localize a button’s image as appropriate.)

When using storyboards to build your interface, use Xcode’s base internationalization feature to configure the localizations your project supports. When you add a localization, Xcode creates a strings file for that localization. When configuring your interface programmatically, use the system’s built-in support for loading localized strings and resources. For more information about internationalizing your interface, see Internationalization and Localization Guide.

Accessibility

Buttons are accessible by default. The default accessibility traits for a button are Button and User Interaction Enabled.

The accessibility label, traits, and hint are spoken back to the user when VoiceOver is enabled on a device. The button’s title overwrites its accessibility label; even if you set a custom value for the label, VoiceOver speaks the value of the title. VoiceOver speaks this information when a user taps the button once. For example, when a user taps the Options button in Camera, VoiceOver speaks the following:

  • "Options. Button. Shows additional camera options."

For more information about making iOS controls accessible, see the accessibility information in UIControl. For general information about making your interface accessible, see Accessibility Programming Guide for iOS.

Symbols

Creating Buttons

init(type: UIButtonType)

Creates and returns a new button of the specified type.

Configuring the Button Title

var titleLabel: UILabel?

A view that displays the value of the currentTitle property for a button.

func title(for: UIControlState)

Returns the title associated with the specified state.

func setTitle(String?, for: UIControlState)

Sets the title to use for the specified state.

func attributedTitle(for: UIControlState)

Returns the styled title associated with the specified state.

func setAttributedTitle(NSAttributedString?, for: UIControlState)

Sets the styled title to use for the specified state.

func titleColor(for: UIControlState)

Returns the title color used for a state.

func setTitleColor(UIColor?, for: UIControlState)

Sets the color of the title to use for the specified state.

func titleShadowColor(for: UIControlState)

Returns the shadow color of the title used for a state.

func setTitleShadowColor(UIColor?, for: UIControlState)

Sets the color of the title shadow to use for the specified state.

var reversesTitleShadowWhenHighlighted: Bool

A Boolean value that determines whether the title shadow changes when the button is highlighted.

Configuring Button Presentation

var adjustsImageWhenHighlighted: Bool

A Boolean value that determines whether the image changes when the button is highlighted.

var adjustsImageWhenDisabled: Bool

A Boolean value that determines whether the image changes when the button is disabled.

var showsTouchWhenHighlighted: Bool

A Boolean value that determines whether tapping the button causes it to glow.

func backgroundImage(for: UIControlState)

Returns the background image used for a button state.

func image(for: UIControlState)

Returns the image used for a button state.

func setBackgroundImage(UIImage?, for: UIControlState)

Sets the background image to use for the specified button state.

func setImage(UIImage?, for: UIControlState)

Sets the image to use for the specified state.

var tintColor: UIColor!

The tint color to apply to the button title and image.

Configuring Edge Insets

var contentEdgeInsets: UIEdgeInsets

The inset or outset margins for the rectangle surrounding all of the button’s content.

var titleEdgeInsets: UIEdgeInsets

The inset or outset margins for the rectangle around the button’s title text.

var imageEdgeInsets: UIEdgeInsets

The inset or outset margins for the rectangle around the button’s image.

Getting the Current State

var currentTitle: String?

The current title that is displayed on the button.

var currentAttributedTitle: NSAttributedString?

The current styled title that is displayed on the button.

var currentTitleColor: UIColor

The color used to display the title.

var currentTitleShadowColor: UIColor?

The color of the title’s shadow.

var currentImage: UIImage?

The current image displayed on the button.

var currentBackgroundImage: UIImage?

The current background image displayed on the button.

var imageView: UIImageView?

The button’s image view.

Getting Dimensions

func backgroundRect(forBounds: CGRect)

Returns the rectangle in which the receiver draws its background.

func contentRect(forBounds: CGRect)

Returns the rectangle in which the receiver draws its entire content.

func titleRect(forContentRect: CGRect)

Returns the rectangle in which the receiver draws its title.

func imageRect(forContentRect: CGRect)

Returns the rectangle in which the receiver draws its image.

Constants

UIButtonType

Specifies the style of a button.

Relationships

Inherits From

Conforms To