iOS Development with Xamarin Cookbook
上QQ阅读APP看书,第一时间看更新

Receiving user input with buttons

In this recipe, we will learn how to use buttons to receive and respond to user input.

Getting ready

We used buttons in Chapter 1, Development Tools, to discuss how to use Interface Builder to add controls to the user interface. In this recipe, we will describe the UIButton class in more detail. Open the FirstViewApp project, which we created in the previous recipe, in Xamarin Studio. Increase the height of the view, which we added, to cover the whole device screen in Interface Builder and save the document.

How to do it...

Perform the following steps:

  1. We will programmatically add a button in our interface. This button will change our view's background color when tapped. Open the FirstViewAppViewController.cs file and enter the following code in the class:
    UIButton buttonChangeColor;
    private void CreateButton ()
    {
      RectangleF viewFrame = this.subView.Frame;
      RectangleF buttonFrame = new RectangleF (10f, viewFrame.Bottom - 200f, viewFrame.Width - 20f, 50f);
      this.buttonChangeColor = UIButton.FromType (UIButtonType.System);
      this.buttonChangeColor.Frame = buttonFrame;
      this.buttonChangeColor.SetTitle ("Tap to change view color", UIControlState.Normal);
      this.buttonChangeColor.SetTitle ("Changing color...", UIControlState.Highlighted);
      this.buttonChangeColor.TouchUpInside += this.ButtonChangeColor_TouchUpInside;
      this.subView.AddSubview (this.buttonChangeColor);
    }
    bool isYellow;
    private void ButtonChangeColor_TouchUpInside (object sender, EventArgs e)
    {
      if (this.isYellow) {
        this.subView.BackgroundColor = UIColor.LightGray;
        this.isYellow = false;
      }  else {
        this.subView.BackgroundColor = UIColor.Yellow;
        this.isYellow = true;
      }
    }
  2. In the ViewDidLoad method, add the following line:
    this.CreateButton ();
  3. Compile and run the app on the simulator. When the button is tapped, the result should be similar to the following screenshot:
    How to do it...

How it works...

In this recipe, we have added a button to the user interface. This button changes the background color of its superview. Furthermore, we have accomplished this without using Interface Builder at all.

Let's see now what the code does. We create the following field that will hold the button object:

// A button to change the view's background color
UIButton buttonChangeColor;

In the CreateButton method, we create the button and set some properties. The method is shown in the following code:

// Create the appropriate rectangles for the button's frame
RectangleF viewFrame = this.subView.Frame;
RectangleF buttonFrame = new RectangleF (10f, viewFrame.Bottom - 200f, viewFrame.Width - 20f, 50f);

First, we assign the view's frame to a new variable named viewFrame. Then, we create a new RectangleF object named buttonFrame. This object will be assigned to the button's Frame property. Now that we have a frame for our button, we can initialize it as shown in the following code snippet:

// Create the button.
this.buttonChangeColor = UIButton.FromType (UIButtonType.System);
this.buttonChangeColor.Frame = buttonFrame;

The button is initialized with the UIButton.FromType(UIButtonType) static method. This method takes one parameter of the UIButtonType type and returns predefined types of buttons that are included in iOS SDK. The UIButtonType.System button enumeration value used here is the default type of button without any borders or background. After the buttonChangeColor object is initialized, we set its frame to the RectangleF value we created earlier.

Now that we have provided an initialization code for the button, we will set its titles (that's right, more than one) as shown in the following code:

// Set the button's titles
this.buttonChangeColor.SetTitle ("Tap to change view color", UIControlState.Normal);
this.buttonChangeColor.SetTitle ("Changing color...", UIControlState.Highlighted);

We call the UIButton.SetTitle(string, UIControlState) method twice. This method is responsible for setting the button's title for each given button state. The string parameter is the actual title that will be shown. The second parameter is an enumeration of the UIControlState type. This parameter indicates the different control states that apply to controls. These control states are as follows:

  • Normal: This is the default idle state of an enabled control.
  • Highlighted: This is the state of the control when a touch-up event occurs.
  • Disabled: This is the state when the control is disabled and does not accept any events.
  • Selected: This is the state when the control is selected. In most cases, this state does not apply. However, it is useful when a selection state is required, like in a UISegmentedControl object.
  • Application: This is the additional control state value for an application's use.
  • Reserved: This is for internal framework use.

So, with the UIButton.SetTitle(string, UIControlState) method, we have set the title that will be displayed when the button is in its default state and the title that will be displayed while the button is being tapped.

After this, we set the button's handler for the TouchUpInside event and add it as a subview to subView using the following code:

this.buttonChangeColor.TouchUpInside += this.ButtonChangeColor_TouchUpInside;
// Display the button
this.subView.AddSubview (this.buttonChangeColor);

Inside the buttonChangeColor_TouchUpInside event, we change the background color of the view according to the Boolean field that we have declared, as shown in the following code:

if (this.isYellow) {
  this.subView.BackgroundColor = UIColor.DarkGray;
  this.isYellow = false;
} else {
  this.subView.BackgroundColor = UIColor.Yellow;
  this.isYellow = true;
}

This is done by setting the view's BackgroundColor property to the appropriate UIColor class instance we want, as shown in the preceding highlighted code. The UIColor object is a class with many different static methods and properties that allow us to create different colored objects.

When you compile and run the app on the simulator, notice the view's color change when you tap the button. Also notice how the button's title changes while the mouse cursor (or a finger on the device) is "touching" the button.

There's more...

In this recipe, we used the UIButton.FromType(UIButtonType) static method to initialize the button. A brief description of each of the enumeration flags of UIButtonType are as follows:

  • System: This is the default type of button.
  • Custom: This is a borderless transparent button. Use this flag when creating custom buttons with images as backgrounds. The button's title is not transparent.
  • RoundedRect: This is the default type of button with rounded corners. As of iOS 7, this type of UIButton is deprecated. Use UIButtonType.System instead.
  • DetailDisclosure: This is a round blue button that reveals additional information related to an item.
  • InfoLight: This is a light-colored button with the letter (i) that represents information display.
  • InfoDark: This is the same as InfoLight; it is shown with a dark color.
  • ContactAdd: This is a round blue button with a white plus sign (+). Usually, this button is displayed to present contact information to add to an item.

Changing the appearance of buttons

For creating custom buttons with the UIButtonType.Custom type, use the UIButton class' SetBackgroundImage and SetImage methods. They both accept one UIImage and one UIControlState parameter so that different images for different control states can be set. When setting images for buttons, be sure to set the UIButton.ContentMode property accordingly, irrespective of whether creating a custom button or not.

The functionality provided by the SetImage and SetBackgroundImage methods can also be accomplished in the corresponding Image and Background fields in the Attributes tab of the Inspector pad in Interface Builder. Select the state for which to set the desired image(s) from the drop-down list box and set the path to the image file, as shown in the following screenshot:

Changing the appearance of buttons

See also

  • The Adding and customizing views recipe
  • The Displaying images recipe
  • The Creating a custom view recipe
  • The Styling views recipe
  • The Creating the UI recipe in Chapter 1, Development Tools