Common Views

Views are the building blocks for constructing a user interface in iOS. The views are used to present content and also to support navigation. Each view represents a particular portion of your user interface and is generally optimized for a specific type of content. Views are subclasses of the UIView class and their properties can be changed in the storyboard properties window. View Porperties

Label

A label displays static text. Labels are often used in conjunction with controls to describe their intended purpose, such as explaining which value a button or slider affects

Purpose

Labels allow the user to:

  • Understand the purpose of controls in an app
  • Receive instructions or context in an app

Configuring the Label properties

The label properties can be changed in storyboard properties window. Label Properties

TextField

Text fields allows the user to input a single line of text into an app. You typically use text fields to gather small amounts of text from the user and perform some immediate action, such as a search operation, based on that text. The text field is a subclass of the UITextField class.

TextField

Configuration

You can configure the properties of the textfield in interface builder. Some properties of the texfield can not be changed with the properties window, they can only be changed in code.

Configure Textfield

Textfiled Delegate

The texfield requires a delegate to handle most of its functions. You will usually set this to be the view controller. The view controller needs to implement the UITextfieldDelegate methods. Xamarin uses events instead of using the iOS delegation pattern.

class TextFieldDelegate : UITextFieldDelegate {
    public virtual void EditingEnded(UITextField textField) { }
    public virtual void EditingStarted(UITextField textField) { }
    public virtual bool ShouldBeginEditing(UITextField textField){ }
    public virtual bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString) {}
    public virtual bool ShouldClear(UITextField textField) { }
    public virtual bool ShouldEndEditing(UITextField textField) { }
    public virtual bool ShouldReturn(UITextField textField) { }
}

Button

Buttons let a user initiate behavior with a tap. You communicate a button’s function through a textual label or with an image. The button is a class of type UIButton.

Buttons

Button Configuration

The properties of the button can be changed in the properties window in the storyboard.

Button Properties

Button events

The default button event is TouchUpInside. The event can be added from the Events tab in the storyboard or directly in code.

Button Click Event

Once you add the click event in the storyboard, Xamarin Studio automatically jumps to code and lets you choose where to create the event handler method.

Button Event Method

Slider

Sliders enable users to interactively modify some adjustable value in an app, such as speaker volume or screen brightness. For example, in GarageBand, sliders allow users to mix different settings for various effects. Users control a slider by moving its current value indicator along a continuous range of values between a specified minimum and maximum.

Slider

Slider Properties

Sliders are simple controls and do not have a lot of properties to configure.

Slider Properties

Slider Events

The default event for the slider is ValueChanged.

partial void OnChangeVolume(UISlider slider)
{
    Console.WriteLine(slider.Value);
}

Slider Event

ImageView

An image view displays an image or an animated sequence of images. An image view lets you efficiently draw an image (such as a JPEG or PNG file) or an animated series of images onscreen, scaling the images automatically to fit within the current size of the view. Image views can optionally display a different image or series of images whenever the view is highlighted.

ImageView Properties

The image view only have the image property to choose the image to display and optional a different image when the image is highlighted.

Image Properties

The imageview by default does not receive user input, you will need to enable User Interaction Enabled for the imageview to receive input.

Loading Images from Asset Catalog

You can choose an image from the Asset Catalog and set the image property. You can also load an image in code from the Assets Catalog or from the Resources folder or from a file.

public override void ViewDidLoad()
{
    base.ViewDidLoad();
    profileImageView.Image = UIImage.FromBundle("placeholder");
}

Loading from the Network

You can also load images from the network. The easiest is to use a library like SDWebImage.

profileImageView.SetImage (
    url: new NSUrl ("http://db.tt/ayAqtbFy"), 
    placeholder: UIImage.FromBundle ("placeholder.png")
);

ActionSheet

Action sheets display a set of buttons representing several alternative choices to complete a task initiated by the user. For example, when the user taps the Share button in an app’s toolbar, an action sheet appears offering a list of choices, such as Email, Print, and so on.

Actionsheet van only be created with code, you can not create them within the storyboard.

var actionSheet = UIAlertController.Create("Choose Event", null, UIAlertControllerStyle.ActionSheet);
var gameViewAction = UIAlertAction.Create("Game Viewing", UIAlertActionStyle.Default, null);
var paintBallAction = UIAlertAction.Create("Paint Ball", UIAlertActionStyle.Default, null);
var dragRacingAction = UIAlertAction.Create("Drag Racing", UIAlertActionStyle.Default, null);

actionSheet.AddAction(gameViewAction);
actionSheet.AddAction(paintBallAction);
actionSheet.AddAction(dragRacingAction);

PresentViewController(actionSheet, true, null);

AlertView

Alert views display a concise and informative alert message to the user. Alert views convey important information about an app or the device, interrupting the user and requiring them to stop what they’re doing to choose an action or dismiss the alert. For example, iOS uses alerts to warn the user that battery power is running low, so they can connect a power adapter before their work is interrupted. An alert view appears on top of app content, and must be manually dismissed by the user before he can resume interaction with the app.

You change the style of the UIAlertController to UIAlertControllerStyle.Alert in order to get an alert.

Alert

var alert = UIAlertController.Create("No connection", null, UIAlertControllerStyle.Alert);
var okAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default, null);
alert.AddAction(okAction);

PresentViewController(alert, true, null);

Segmented Button

A segmented control is a horizontal control made of multiple segments, each segment functioning as a discrete button. The segment control is of type UISegmentControl.

Segmented Control

Segment Control Properties

Segmented Control properties can be in the storyboard properties, but some properties can only be changes in code.

Segmented Control Properties

Segmented Control Events

The default event for the segmented control is the ValueChanged event.

partial void DidSelectSegment(UISegmentedControl sender)
{
    Console.WriteLine(sender.SelectedSegment);
}

Switches

A switch lets the user turn an option on and off. You see switches used throughout the Settings app to let a user quickly toggle a specific setting. The switch is type UISwitch.

Switch

Switch Configuration

The switch control properties can be configured in the storyboard. The switch have a state property which determines whether its checked or not.

Switch Properties

Switch Events

The default event for the switch is ValueChanged.

partial void SwitchValueChanged(UISwitch sender)
{
    Console.WriteLine(sender.Selected);
}

Stepper

A stepper lets the user adjust a value by increasing and decreasing it in small steps. Steppers are used in situations where a user needs to adjust a value by a small amount. The stepper control is of type UIStepper.

Stepper

Stepper Configuration

Configuration of the properties can be done in the storyboard properties or in code.

Stepper Properties

Stepper Events

The default event of the stepper control is the ValueChanged event.

partial void StepperValueChanged(UIStepper sender)
{
    Console.WriteLine(sender.Value);
}

Date Picker

A date picker is a control used for selecting a specific date, time, or both. It also provides an interface for a countdown timer, although it does not implement the functionality. Date pickers provide a straightforward interface for managing date and time selection, allowing users to specify a particular date quickly and efficiently. The date picker is of type UIDatePicker.

Date Picker

Date Picker Configuration

The date picker can be configured in the properties section of the storyboard. Some properties can obly be made in code.

Date Picker Properties

Date Picker Events

Map View

Scroll View

Table View

Web View

Split View

Collection View

Change Status Bar Color

Starting from iOS 9 you can use the Appearance API to change the color of the status bar. If the content is dark you can make the status bar white and if your content is white you can make the appearance of the status bar darker.

  1. Open the Info.plist file add a new new. Use the Source View. The key is UIViewControllerBasedStatusBarAppearance and set it to NO Change Status Bar Appearance
  2. Go back to the Info.plist file and change Status bar syle to Light under the Deployment Info section. Light Status Bar

Overview

Typically images are displayed using the built-in UIImageView. UIImageView supports both displaying a single image as well as animating a series of images.

Usage

With Interface Builder it’s pretty easy to add and configure a UIImageView. The first step is to drag the UIImageView onto your view.

Add UIImageView|700

Then open the UIImageView properties pane and select the image asset (assuming you have some images in your project). You can also configure how the underlying image is scaled to fit inside the UIImageView.

Configure UIImageView|700

Scale Types

Supporting Multiple Screen Densities

Working with UIImages

Loading Images from the Network with AFNetworking

The built-in UIImageView works great when the image is locally available, but doesn’t have great support when the image needs to be downloaded over the network. This is where AFNetworking comes in handy. The following steps walk through how to pull in and use AFNetworking for working with images over the network.

Setup AFNetworking

First, we need to use [[CocoaPods]] to pull in AFNetworking (pod 'AFNetworking').

After a pod install, we can now import AFNetworking and use the additional methods that are available for UIImageView:

import AFNetworking

class myViewController {
    
    // Outlet for ImageView
    @IBOutlet weak var myImageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let myImageUrlString = "https://i.imgur.com/tGbaZCY.jpg"

        // AFNetworking extension to UIImageView that allows
        // specifying a URL for the image
        myImageView.setImageWithURL(NSURL(string: myImageUrlString)!)
    }
}

Improving the User Experience

There are a couple of enhancements that can be done when working with images being pulled from the network to improve the user experience.

Fading in an Image Loaded from the Network

It can be a little jarring for the user to have images pop into place once they are downloaded from the network. To prevent this, it’s a good idea to fade images in as they are downloaded.

let imageUrl = "https://i.imgur.com/tGbaZCY.jpg"
let imageRequest = NSURLRequest(URL: NSURL(string: imageUrl)!)

self.myImageView.setImageWithURLRequest(
    imageRequest,
    placeholderImage: nil,
    success: { (imageRequest, imageResponse, image) -> Void in
        
        // imageResponse will be nil if the image is cached
        if imageResponse != nil {
            print("Image was NOT cached, fade in image")
            self.myImageView.alpha = 0.0
            self.myImageView.image = image
            UIView.animateWithDuration(0.3, animations: { () -> Void in
                self.myImageView.alpha = 1.0
            })
        } else {
            print("Image was cached so just update the image")
            self.myImageView.image = image
        }
    },
    failure: { (imageRequest, imageResponse, error) -> Void in
        // do something for the failure condition
})

Loading a Low Resolution Image followed by a High Resolution Image

Since pulling down high resolution images over the network takes time, it’s common to first show a low resolution image so the user sees something in the UIImageView and then load the higher resolution image immediately afterwards.

let smallImageRequest = NSURLRequest(URL: NSURL(string: smallImageUrl)!)
let largeImageRequest = NSURLRequest(URL: NSURL(string: largeImageUrl)!)

self.myImageView.setImageWithURLRequest(
    smallImageRequest,
    placeholderImage: nil,
    success: { (smallImageRequest, smallImageResponse, smallImage) -> Void in
        
        // smallImageResponse will be nil if the smallImage is already available
        // in cache (might want to do something smarter in that case).
        self.myImageView.alpha = 0.0
        self.myImageView.image = smallImage;
        
        UIView.animateWithDuration(0.3, animations: { () -> Void in
            
            self.myImageView.alpha = 1.0
            
            }, completion: { (sucess) -> Void in
                
                // The AFNetworking ImageView Category only allows one request to be sent at a time
                // per ImageView. This code must be in the completion block.
                self.myImageView.setImageWithURLRequest(
                    largeImageRequest,
                    placeholderImage: smallImage,
                    success: { (largeImageRequest, largeImageResponse, largeImage) -> Void in
                        
                        self.myImageView.image = largeImage;
                        
                    },
                    failure: { (request, response, error) -> Void in
                        // do something for the failure condition of the large image request
                        // possibly setting the ImageView's image to a default image
                })
        })
    },
    failure: { (request, response, error) -> Void in
        // do something for the failure condition
        // possibly try to get the large image
})

References