Part 4 - Buttons

PDF for offline use

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-03

The UIButton class is used to represent various different styles of button in iOS screens. This section introduces the different options for working with buttons in iOS.

The UIButtonclass represents a button control in iOS. Button properties can be edited in the Properties Pad of the iOS designer:

Button Types

An example of each built-in button type is shown here:

In iOS 7, the default Button style is the System style:

Button State

You can set text, font and color properties for each button state by changing the State Config:

Setting different properties for each state allows you to communicate more information to the user (eg. make the text color grey for the disabled state). You can switch between each state to set the values using the iOS Designer, or you can do it programmatically as illustrated by the code example below:

button1.SetTitle("Click me", UIControlState.Normal);
button1.SetTitleColor(UIColor.Black, UIControlState.Normal);
button1.SetTitle("disabled", UIControlState.Disabled);
button1.SetTitleColor(UIColor.Gray, UIControlState.Disabled);

Custom Button Types

When you set the Custom button type, the object has no default rendering. You can configure the button’s appearance by setting an image for the different states. For example, the following code demonstrates how to add different images for the Normal, Highlighted and Selected states:

button4.SetImage (UIImage.FromBundle ("Buttons/MagicWand.png"), UIControlState.Normal);
button4.SetImage (UIImage.FromBundle ("Buttons/MagicWand_Highlight.png"), UIControlState.Highlighted);
button4.SetImage (UIImage.FromBundle ("Buttons/MagicWand_On.png"), UIControlState.Selected);

Depending on whether the user is touching the button or not, it will be rendered as one of the following images (Normal, Highlighted and Selected states respectively):

Button Behavior

Buttons are not very useful unless they do something when clicked! In iOS you can respond to the TouchUpInside event like this:

button1.TouchUpInside += (sender, e) => {
    label1.Text = "button1 clicked";
};

The code example above changes the button text to indicate that the button was clicked.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.