Tag Archives: ios

Adding thumbnail images to list rows in the iOS List App with Xamarin

This tutorial will show you how to add a thumbnail image to each row of the Cities list in the iOS List app we made in the previous two tutorials. This is what the app will look like…

image1

Step 1

To get started, open the Main.storyboard file in the iOS List App solution. Resize the labels on the table row on the main screen and move them to the right side of the table row. Then drag an ImageView element from the toolbox on to the left side of the table row. Change the ImageView element’s name to cityImageView.

image2

Step 2 

Make sure you have added your images to your project (this was explained in the previous tutorial).

image3

Also make sure you have added public string ImagePath; to your code as seen on line 76 of the CitiesViewController.cs file below (this was also explained in the previous tutorial).

Click image to see larger version.
Click image to see larger version.

For each city in your list, you should also have specified the ImagePath value (location of the image and its filename) in the CitiesViewController.cs file.

Click image to see larger version.
Click image to see larger version.

Step 3

In the CityTableViewCell.cs file, add the following highlighted line to set the image displayed for each row of the City class. This will get the images to display on each row. Save all of your files.

image6

Step 4

Now just go and test your app. This is what the thumbnail images should look like:

preview

Adding a Details screen to the List app for iOS with Xamarin

In this tutorial, we will look at how to extend the iOS List app we made in the previous tutorial by adding a Details screen that will display more details about item the user has selected from the list.

This is what the app will look like…

detailsscreen

Note: The title bar of the app will normally display and should be presented when the app is tested on an actual iOS device, but a bug in the iOS Simulator used here prevents the title bar from showing.

Step 1

Drag a Navigation Controller from the Toolbox on to your storyboard.

image3

Right-click and Delete the Root View Controller that is not required (you may have to delete twice).

image4

Step 2

Hold down the Control (Ctrl) key while clicking and dragging from the Navigation Controller to the Table View screen. Then select Root.

image5

Step 3

Drag a View Controller from the Toolbox on to your storyboard next to the main screen.

image6

Step 4

Add an ImageView element and a Label element to your screen. The default Text value for the label can be set to City Name. You also need to give both elements a name. Set the Name value for the Image View to cityImageView and the Name value for the label to cityNameLabel.

image7
When you give the ImageView or Label element a name you will see a yellow warning icon in the Name field. Click this icon and then type in DetailsViewContoller and press the Enter key to generate a new class and codebehind for this screen.

image8

Step 5

Now Control-click (Crl + click) and drag from the row on the main screen to the new details screen and select Show. This means that when the user selects a city from the list, they will be taken to the city details screen.

image9

You can also double-click on the main screen’s title to change it.

image10

Step 6

Click on the arrow between the main screen and details screen. On the Properties panel, set the Identifier value to DetailsSegue. Remember its name because it will be used in the code.

image11

 

Step 7

Open the CitiesViewController.cs file and scroll down to the City class. We need to add a new property called ImagePath which will contain the image for each city in the class.

image12

 

Step 8

Right-click the project folder and select Add > New Folder. Name this folder Images.

image13

Now right-click the Images folder and click Add > Add Files from Folder.

image14

Browse for the folder containing your images and then click Open.

image15

Select the desired images and then click OK.

image16

Select Copy the file to the directory and Use the same action for all selected files. Then click OK.

image17

Step 9

Go back to the CitiesViewController.cs file and for each city in the cityList, add the lines highlighted below to specify the ImagePath for each city’s image. Remember to add a comma to the end of the line before the ImagePath line (see the commas at the end of lines 22 and 31).

image18

Step 10

Go to the DetailsViewController.cs file and add the public City selectedCity; line to the DetailsViewController : UIViewController class. Save the file.

image19

 Step 11

Now you need to add a PrepareForSegue override method. You can add this method after the GetCell method. Start typing public override PrepareForSegue and then select the PrepAreForSegue method from the list by double-clicking it or pressing Enter to autocomplete.

image20

Step 12

Add the following code to the new PrepareForSegue method. This will check if the segue is the DetailsSegue (in other words, if the user tapped one of the rows from the table on the main screen that takes them to the details screen). Then it will get the relevant data from the selected row to be displayed on the details screen.

image21

Step 13

Back in the DetailsViewController.cs file, add a public override ViewWillAppear method. To do this, start typing public override ViewWillAppear and then select that method from the list.

image22

Step 14

Inside the new ViewWillAppear method (which runs as soon as the second screen loads), add the following highlighted lines of code (replacing any existing default code inside the method). This will set the label text to display the name of the selected city and will also set the ImageView to display the image representing the selected city.

image23

All done! Make sure you save your files and then you can test your app!

You can extend this app by adding more properties to each City item so that the Details page can display more information about a city such as points of interest, activities, and even its location on a map.

In the next tutorial we will look at how to add thumbnail image previews to each row in the list.

Creating a List app for iOS with Xamarin

In this tutorial, we will look at how to create a list app for iOS. The example used in this tutorial will be a list of cities. When the name of a city in the list is tapped by the user, details about that city will be presented (we will achieve that part in the next tutorial).

image1
The iOS list app.

Step 1

Begin by clicking File > New Solution in Xamarin Studio and then select iOS App and Single View App. Then click Next.

image2

Step 2

Give the app a name (the app in this example will be called ListAppIOS), select the target iOS version and then click Next.

image3

Step 3

Confirm the project name, solution name, project location and click Create.

image4

Step 4

Open the Main.storyboard file and select an iPhone model from the View As drop-down list (eg. iPhone 6).  Then drag a Table View Controller on to the storyboard next to the main screen.

image5

Step 5

Now right-click on the main screen (on the left) and select Delete to remove this screen as it is no longer needed (you may need to click Delete twice). The Table View controller will now be the first screen that loads when the app launches.

image6

Step 6

Now that the first screen is deleted, the ViewController.cs file will no longer be needed so we can delete it. Select the ViewController.cs file, right-click it and select Remove.

image7

Then select Delete when the dialog box appears asking you.

image8

Step 7

Now you will need a class that will control the table view controller. Select the Table View Controller by clicking on the bar at the bottom of it. You should see the Class property on the Properties panel. At the moment it is empty but it needs a class so we can create the class here.

image9

Click in the Class property field and type in a name for the new class eg. CitiesViewController. Then press Enter. You’ll notice a new C Sharp (.cs) file is created for this new class and it will appear in the solution panel.

image10

At this stage, if you simulate the app you will see an empty list on the main screen as shown below.

image11

Step 8

Now go back to the Main.storyboard file and click on the title bar at the top of the app screen. We need to add a reuse identifier that allows the app to re-use rows on the table on the app screen as the user scrolls down the screen rather than having to generate new rows. Change the Identifier value to City.

image12

Step 9

Now open the CitiesViewController.cs file so that you can start populating a list of cities in the table view controller. Adding the using System.Collections.Generic; line allows us to use the List class that can contain many elements. Before we start creating a list of cities we need to define what a city is by creating a City class and giving it some properties such as its name (string), the country and state it belongs to (strings) and its population (integer).

image13

Step 10

Once we have created the class City, we can create a List that will contain many elements and set its type to City so that every time added to the list will be a city. First we give the list its name and set its type, and then we can create the list.

image14

Step 11

Now that we have create the list, we can populate the table view with data from the list.

image15

Step 12

Now we need to override a few of methods: NumberofSections, RowsInSection, and GetCell. For each method, as you type public override and press the spacebar key, you will be presented with methods that you can select from. Start typing the name of the method you want to override and then double-click it to add the override method.

The first method we override is NumberofSections which can be set to return 1 because only one section is needed in the table. As shown below on line 36, we set return to 1.

The second method is RowsInList which is set to return CityList.Count; (this will make as many rows in the table as there are cities in the list) as seen on line 41.

The third method we override is GetCell which is the method that will allows us to get a re-usable cell, modify its values, and return it to the table view. We create a variable called cell and we use the name of the reuse identifier we set for the table view controller back in Step 8 (line 46). We also create a variable called data which set each row to contain data from the city list (line 47) and we set the text on the TextLabel (a default TextLabel already exists) for the cell to be the name of the city for that row (line 48). Lastly, we return cell (line 49).

Here are the three methods once they have been added.

image16
Click the image to see a larger version.

Step 13

At this stage, if you test the app in the simulator you will see the list with the name of each city on each row of the list (we only have two rows in this list but you can add many more to your list).

image17

Now we need to customised the rows in the list to improve their appearance and so they can display some more information about each city.

Step 14

Now we will add more details to each row in the table view (the state and country). Open the Main.storyboard file and click once on the row at the top of the table view. Go to the Class field. We will create a class that will represent the row.

image18

The Class field should currently say UITableViewCell (if it says UITableView, then you may have clicked twice on the row on the screen. De-select the row, then click it once making sure that that the Class field says CityTableViewCell. Type in CityTableViewCell in the Class field and press the Enter key on the keyboard.

image19

You should now see the CityTableViewCell.cs file in the solution panel. Double-click it to open the file – we will now start adding code to this new C Sharp file.

image20

Step 15

Now we need to create a local private variable called City just for this class. Then we need to create a global variable for this data so it can be accessed anywhere. In this, we will have a getter which will get the method that we will access the value of the property (it will return bookData – the private property). Then we set the bookData to the value we are getting.

image21

Go back to the Main.storyboard file. Drag a Label element on to the row at the top of the screen.

image22

Resize the row at the top of the screen because it will need to fit more labels by dragging it down from the circle at the bottom of the row.

image23

Step 16

Now add more Label elements to the screen to display the city name, state name, country name, and population. Arrange and resize the labels so they will be able to fit their text in. Give each label a default property for Text so that you know what each label represents. You can also change the colours or font style. For example, the city name label below is set to Size 19pt Semibold.

Change the Name property for each Label. The labels on this screen have the following names:

  • cityNameLabel (this will display the city name)
  • stateCountryLabel (this will display the state and country separated by a comma)
  • populationLabel (this will display the city’s population)

image24

Step 17

Go back to the CityTableViewCell.cs file. We now need to access the labels from the screen that we created in Step 16 and set the text on the labels to match the properties from cityData when the the cityData property receives its value. Add the lines of code below and then save the file.

Note that the state and country are added together with a comma and space in between them. Also note the #,##0 inside the ToString() brackets – this will place commas between the hundreds and thousands for population when displayed on the populationLabel to improve formatting.

image25
Click the image to see a larger version.

Step 18

Go back to the CitiesViewController.cs file. Instead of simply getting a cell, we will now get a cell as CityTableViewCell so we need to add the extra code to the GetCell method as highlighted on line 46 of the code below.

image26
Click the image to see a larger version.

We also need to change the code so that instead of having cell.TextLabel.Text = data.Name; we will now just have cell.cityData = data;

image27
Click the image to see a larger version.

This means we are no longer accessing a property of the data but instead we are just passing the city. Now it is time to test the app. When you test your app in the simulator you may notice some problems with the formatting of your rows such as the row height or overlapping text as seen below. We will look at how to fix this in the next step.

image28

Step 19

After testing, you may realise that you need to change the font size for labels, label width/height, or placement of labels. You may also see overlapping text or items that appear to be in the wrong row. If you see this, you may need to adjust the row height. Click on the Table View (not the row) and then click on the Layout tab on the Properties panel. Under Table View Size, change the Row Height value to something more suitable and test your app. Keep adjusting the value and testing as needed. In this example app, the Row Height value has been changed to 115.

image29

That’s it! Now you can go and test your app! If you want to add a detail screen for each item in the list, then check out the next tutorial.

Passing data between screens on iOS with Xamarin

In this tutorial you will learn how to create an iOS app that can pass data from one screen to another. This will be demonstrated in an example app that will ask the user for their age and will then convert their age to into animal years (of different types of animals). The user will select an animal by tapping a button and then the result will be displayed on the same screen. Tapping a button will take the user to another screen that grabs information from the first screen and displays a fact. The app will look like this…

ipd1

Step 1

Open Xamarin and click File > New Solution to get started. Give your app a name (the app is called AnimalAgeCalculatorIOS in this example). Select a target iOS version and click Next.

ipd3

Step 2

Confirm the project and solution name as well as the project location. Click Create.

 

ipd4

Step 3

Open the Main.storyboard file in the Resources folder and drag a Label on to the screen. The label in this example app is given the Text value Enter your age in years.

ipd5

Then drag a Text Field element on to the screen with the placeholder text Age. Give this Text Field the Name ageTextField.

ipd6

Step 4

Add another label with the text value Convert to… and then four buttons with the following names:

  • dogButton
  • catButton
  • goatButton
  • hamsterButton

Then add another label with the text value Your result and a button with the text value Find out more and the Name detailsButton – as shown below.

ipd7

Step 5

Now open the ViewController.cs file and add a TouchUpInside+= event for the dogButton element inside the ViewDidLoad() method. As you type in the line dogButton.TouchUpInside+= and press the spacebar on your keyboard you will be presented with some options. Double-click on DogButton_TouchUpInside to create a new method of the same name. If you don’t see the option immediately, start typing it in until it shows up in the list and then double-click it to add the new method for the touch event.

ipd8

Step 6

Now repeat the last step for each of the buttons (adding a new method for the TouchUpInside events for each of the four animal buttons).

ipd9

Step 7

Add the following variables to the ViewController : UIViewController class:

  • float age; (stores the user’s age)
  • float animalAge; (stores the age of the user in selected animal years)
  • string animal; (stores the name of the animal the user selected)

ipd10

Step 8

Now add the following highlighted code in the methods for the button touch events. This will get the user’s age from the text field and store it in the age variable as a float value. The animal’s age will also be calculated (based on which animal button the user pressed) and stored in the animalAge variable as a float value. The selected animal’s name will be stored in the animal variable as a string value. The label displaying the result will also be updated.

ipd11

Step 9

Now drag a Navigation Controller from the toolbox onto the screen in the Main.storyboard file.

ipd12

Step 10

Right-click and delete the Root View Controller screen on the left (may have to do this twice).

ipd13

Step 11

Hold down the Control (Ctrl) key while clicking and dragging from the Navigation Controller screen (on the left) to the main screen (on the right). You’ll see a blue line appear connecting the two screens together and a menu will also appear.

ipd14

When the menu appears make sure you select Root.ipd14b

 

 

 

Step 12

Now drag a View Controller from the toolbox on to the screen and place it on the right side of the main screen. This will be the second screen in the app.

ipd15

Step 13

Drag a Label on to the screen. Give it a name and you will notice that a warning icon appears. Clicking on the warning icon will reveal the warning message.

ipd16

The warning message tells us that there is no codebehind for this screen so we will need to create one. This will create a second ViewController.cs file for this screen. Give it the name ResultViewController and press the Enter key.

ipd17

In the solution panel you should now see the ResultViewController.cs file in the list. This file is where we add the code for the second screen.

ipd18

Step 14

Now Control (Ctrl) click the Find out more button on the main screen and while holding down the mouse key, drag on to the second screen and release. A small menu will appear. Select Show (this means when the button is pressed, it will show the second screen).

ipd19

Step 15

Now go back to ViewController.cs and add a new method. Start typing public override PrepareForSegue and then double-click the method shown in the list to create it.

ipd21
Click the image for a larger version.

Add the following highlighted code to the new PrepareForSegue method. This will create a variable for the second screen/view controller and the two variables that will have their values passed to the second screen are also specified here.

ipd22
Click the image for a larger version.

Step 16

Now go to the ResultViewController.cs file (for the second screen) and add the following highlighted code in the ResultViewController : UIViewController class. This will declare the animalAge and animal variables with initial values of 0f for animalAge and an empty string for animal.

ipd23
Click the image for a larger version.

Step 17

Now drag a Text View element on to the second screen with the Name resultLabel and the Text value of Your result. Resize it so it has plenty of room for text.

ipd24

Step 18

Go back to the ResultViewController.cs file and add the ViewDidLoad method.

ipd25
Click the image for a larger version.

Inside the ViewDidLoad method, add the following highlighted code. This will display the result to the user based on their animal age and selected animal.

ipd26
Click the image for a larger version.

Step 19

Now drag a Button element from the toolbox on to the second screen in the Main.storyboard file and give it the Name value backButton and the Text value Back.

ipd27

Step 20

Now Control (Ctrl) click and drag from the Back button on the second screen to the main screen and click Show when the menu appears after releasing the mouse button. This will make the app take the user back to the main screen when they press the Back button.

ipd28

Step 21

The final step is to allow the user to dismiss the keyboard on the main screen when the keyboard is no longer required. Go back to the ViewController.cs file and add an override TouchesBegan method as shown below.

ipd29
Click the image for a larger version.

Inside the new override method, add the following highlighted line of code which will end editing and dismiss the keyboard when the user no longer requires it.

ipd30
Click the image for a larger version.

That’s it! Now go and save all your files and test your app.

Play audio in an iOS app with Xamarin

This tutorial explains how to play audio files in the background in an iOS app. An audio file can play when a screen loads or when an event occurs (such as a button press or change in a variable’s value). The example app in this tutorial will play a sound when a button is pressed. We will also look at how to use the Vibrate function in an iPhone to make the phone vibrate as well as playing a sound.

Here is what this app will look like:

ia_app

Step 1 

Open Xamarin and click File > New Solution. Then select iOS App and SingleView App as the project template. Click Next.

ia1

Step 2

Give your new app a name and select a target iOS version. Click Next. On the following screen, confirm the project and solution name and then click Create.

ia2

Step 3

When the solution opens, right-click on the project folder. Select Add > New Folder.

ia3

Give the new folder the name Sounds.

ia3b

Step 4

Right-click on the new Sounds folder and select Add > Add files from folder.

ia4

Step 5

Navigate to the folder which contains the audio file(s) you wish to use in your app. Click Open.

ia4b

Step 6 

Select the audio files you wish to include in the project (for this example, we will use an MP3 file called mysound.mp3). Click OK.

ia5

Then select Copy the file to the directory and click OK. This file will be copied to the project’s Sounds folder. You should then be able to see the audio file in the Sounds folder within the project folder from the Solution panel.

ia5b

Step 7

Right-click on the audio file in the Sounds folder. Select Build Action and set to BundleResource (if this does not work during testing, try selecting Content instead).

ia6

Step 8

Open the Main.storyboard file. Change the View to your desired iPhone/iPad model. Drag three Button elements on to the screen as shown below. Give the first button a Name of playSoundButton and the text value ‘Play sound’. Give the second button a Name of playSoundVibrateButton and the text value ‘Play sound and vibrate’. Give the third button a Name of vibrateButton and the text value ‘Vibrate’. Save the file.

ia7
Click the image to see a larger version.

Step 9

Open the ViewController.cs file and add the following two highlighted lines of code. The first two highlighted lines allow us to access audio tools and lower-level classes. url defines where the location and name of the audio file, while mySound is the name of the variable holding the sound file.

ia8
Click the image to see a larger version.

Step 10

Now add the following two highlighted lines of code in the ViewDidLoad method. Here we define the location and filename of the audio file as well as directing the mySound variable to use this audio file. Replace mysound.mp3 with the name of your sound file.

ia9
Click the image to see a larger version.

Step 11 

Now create a TouchUpInside event for each of the three buttons in the ViewDidLoad method. Inside the new methods for each TouchUpInside event, add the lines of code shown below.

  • SystemSound.PlaySystemSound(); will just play the sound
  • SystemSound.PlayAlertSound(); will play the sound and vibrate the phone
  • SystemSound.Vibrate.PlaySystemSound(); will just vibrate the phone
ia10
Click the image to see a larger version.

That’s it! Now go and test the app!

Adding more screens to an iOS app

This tutorial explains how to add more than one screen to your iOS app and link screens together using buttons. We will use a simple example for this tutorial as show below…

iosmultiscreenapp

Watch the video below or scroll down to read the step-by-step instructions and sample code.

Video

Step 1

Start by creating a new solution (click File > New Solution).

ims1

Step 2

Give your app a name, select a minimum supported iOS version and click Next.

ims2a

Confirm the project and solution names, the project folder location and click Create.

ims2b

Step 3 

Open the Main.storyboard file and drag a Button element on to the screen. Give it a name and change its text value.

ims3

Step 4

Drag a Navigation Controller anywhere onto the storyboard. It should look like this…

ims4

Step 5

Right-click the Root View Controller and click Delete.

ims5

Step 6

Hold down the Ctrl (Control) key while dragging the Navigation Controller screen to your main screen (you will see a blue line linking the two screens together). The select Root from the list of options – this will make the main screen the root screen (the screen that loads first when the app starts running).

ims6

Step 7

Now drag a View Controller element onto the storyboard and place it to the right side of your main (root) screen. This will create a new screen which will be the second screen in your app.

ims7

Step 8

Hold down the Ctrl (Control) key while clicking and dragging the button on the main screen to the second screen. When you see the list of options appear, select Appear.

ims8

Step 9

Now we can add a Button to get from the second screen back to the main screen. Drag a button element on to the second screen. Give it a name. When you name the first element that you add to a new screen, you will see a yellow warning icon. Click it and then you will need to type in the name of the new ViewController for this screen  (for example, ScreenTwoViewController)– the name you provide will be the name of a new C# file that will contain the code for this screen. Change the Title property of the button the Back.

ims9

Step 10

Now click on the new button on the second screen. Hold down the Ctrl (Control) key while dragging this button to the main screen. Click on Show. This will make the Back button take the user back to the main screen when they tap it.

ims10

Lastly, double-click on the main screen’s title so you can rename it.

ims11

That’s it! Now you can test out your app.

Making a Cookie Clicker game for iOS

In this tutorial we will make a Cookie Clicker game for iOS mobile devices using Xamarin.We made the same app for Android in a previous tutorial and now we are going to make it for iOS devices. You will also learn how to use images for buttons instead of plain text.

This is what the basic working app will look like but you can improve the look of it by change the text and background colours and by adding more options.

iOS Cookie Clicker app
iOS Cookie Clicker app

Watch the video below or scroll down for the full instructions and sample code.

Video

Step 1

Start a new Solution (File > New > Solution). Select App under iOS and then select Single View App. Click on Next.

ioscc1

Step 2

Give your app a name, select the minimum iOS version you want to support and click Next.

ioscc2

Step 3

Give your project and solution a name (you can keep it as the default) and then choose the location where you will store your project (eg. the Projects folder). Then click on Create.

ioscc3

Step 4

Open the Main.storyboard file (in the Resources directory). Change the view from Generic to the iPhone model you are targeting (eg. iPhone 6S).

ioscc4

Step 5

Drag a Button element on to the screen from the Toolbox.

ioscc5

Step 6

You will need a cookie image for your app. Once you have an image on your computer, select the Resources folder. Click the cog icon, then Add > Add Files from Folder.

ioscc6

Step 7

Find the folder that contains your cookie image. Then click on Open.

ioscc7

Step 8

Click the checkbox next to the image you want to use and then click OK.

ioscc8

Step 9

Choose Copy the file to the directory and then click OK.

ioscc9a

You should now see the image in the Resources directory.

ioscc9b

Step 10

Now select the Button you added earlier and from the Widget tab on the Properties panel, scroll down until you see the Background property. Click the dropdown box and choose the image you want to use (eg. cookie.png). Alternatively, type in the filename in the text box.

ioscc10

Now you have a cookie image as the background for your button. However, the button is very small so it will need resizing.

ioscc10b

Step 11

Click and drag the corners of the button to enlarge it so that the background image of the cookie is nice and clear.

ioscc11

Step 12

Now go and remove the Default title value under Title on the Properties panel so that the button text is no longer visible on the button.

ioscc12

Step 13

Add a Label element to the screen under your cookie button and change its Text value to say ‘0 clicks’.

ioscc13

Step 14

Change the Name of the Button element to cookieButton.

ioscc14

Step 15

Change the Name of the Label element to clicksLabel.

ioscc15

Step 16

Now all that remains is adding the code that will count and display the number of clicks. Open the ViewController.cs file to begin coding.

ioscc16

Step 17

Firstly, create a variable called clicks that will contain an integer value. Its initial value should be 0 before any clicks have been recorded. Inside the public partial class ViewController : UIViewController section, add the following line of code:

int clicks = 0;

ioscc17

Step 18

Now you need to add a button touch event so that every time the cookie button is touched, the clicks variable’s value will increase by 1. To do this, go to the ViewDidLoad method and make some new space under the base.ViewDidLoad() line. Start typing cookieButton.TouchUpInside+= and then press the Spacebar. As you do this, you will see a list of options. Double click the CookieButton_TouchUpInside option to create a new method.

ioscc18

After creating the new CookieButton_TouchUpInside method, you can now add code inside the method that will run when the cookie button is touched by the user. This code should increase the clicks variable by 1 and display the number of clicks every time the button is touched.

ioscc18b

Step 19

Add the following code inside the CookieButton_TouchUpInside method:

clicks++;
clicksLabel.Text = clicks.ToString() + “ clicks!”;

This code will increase the clicks variable by 1 every time the button is tapped as well as displaying the value of the variable and concatenating (joining) the value to the text ‘ clicks!’ – for example 20 clicks! Note that the clicks variable’s value has to be converted to a string before it can be displayed on the button.

ioscc19

Now you can test the app!

ioscc19b

When you test the app, click or touch the cookie button and you should see the number of clicks displayed increased, as shown below.

iOS Cookie Clicker app
iOS Cookie Clicker app

Try extending the app by adding some buttons with the options to ‘buy’ items or unlock items after a certain number of clicks. You could also use a timer to increase the number of clicks automatically over a period of time (eg. 5 clicks every second). You might also like to change the colour of the text and the background of the app.

Sample C# code

Here is the sample C# code for the ViewController.cs file (please note that the namespace should match the project/solution/app name of your app. It is called CookieClickerIOS in this example.

using System;

using UIKit;

namespace CookieClickerIOS
{
  public partial class ViewController : UIViewController
  {
    int clicks = 0;

    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.

      cookieButton.TouchUpInside+= CookieButton_TouchUpInside;

    }

    void CookieButton_TouchUpInside (object sender, EventArgs e)
    {
      clicks++;
      clicksLabel.Text = clicks.ToString () + " clicks!";
    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
  }
}

Improving on the iOS Temperature Converter App

In this tutorial we will look at how to improve the code in the Temperature Converter App for iOS from the previous tutorial. If you have tested the app yourself, you might notice that the app works great when the user enters only numbers. However, what happens when a user enters nothing or enters something other than numbers (such as a letter or other character)? The app will crash!

We will look at how to prevent such errors from occurring so that the app won’t crash if the user accidentally (or deliberately) enters non-numeric values or nothing at all. This is something known as data validation.

The code below is from the same app but has some new code added to it. All of the code is commented, explaining what each new line does. None of the design elements (buttons, labels, text fields) have been changed in any way.

Sample code

Here is the new and improved code for the ViewController.cs file.

// need to add using System; line to access math functions
using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      //  Create a button touch event for the Convert to Celsius button
      cButton.TouchUpInside+= CButton_TouchUpInside;
      //  Create a button touch event for the Convert to Fahrenheit button
      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = tempTextField.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse (tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create fResult variable which stores result of C to F conversion
          float fResult = temp * 1.8f + 32f;
          // Change fResult to decimal data type and round to 2 decimal places
          decimal fResultRounded = Math.Round ((decimal)fResult, 2);
          // Display result on the screen
          resultLabel.Text = fResultRounded.ToString () + " degrees Fahrenheit";
        }
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultLabel.Text = "Enter numbers only";
        }
      // If nothing was entered by user, ask user to enter a number
      }
      else {
        resultLabel.Text = "Enter a number to convert";
      }

    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = tempTextField.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse(tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create cResult variable which stores result of F to C conversion
          float cResult = (temp - 32f) / 1.8f;
          // Change cResult to decimal data type and round to 2 decimal places
          decimal cResultRounded = Math.Round((decimal)cResult, 2);
          // Display result on the screen
          resultLabel.Text = cResultRounded.ToString () + " degrees Celsius";
        } 
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultLabel.Text = "Enter numbers only";
        }
      }
      // If nothing was entered by user, ask user to enter a number
      else {
        resultLabel.Text = "Enter a number to convert";
      }

    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}

Creating your first iOS app

This tutorial will show you how to create a Temperature Converter app for iOS devices using Xamarin. We made the same app for Android in a previous tutorial and now we are going to make it for iOS devices. The app will look like this…

iosapp

Although we will be using Xamarin for designing and coding the app, you will still need to have XCode installed on your Mac device (click here for detailed installation instructions).

Watch the video below or scroll down to view the step-by-step instructions and sample code.

Video

Step 1

To get started, open Xamarin and begin a New Solution.

ios1

Step 2

Select App under iOS and then select Single View App (C#). Click on Next to continue.

ios2

Step 3 

Give your app a name. In this case, it will be called TempConverter. You also need to select a minimum iOS version you want to support. In this case, the target version is iOS 9.1. Make sure the target version is either an older or same version of iOS that you will be using to run the app on. Click Next to continue.

ios3

Step 4

Now just confirm the project and solution name (making sure it is not the same name as a solution that already exists in your projects folder) as well as the project folder location and click Create.

ios4

Step 5

Once the new solution has loaded, Xamarin will automatically open a file called AppDelegate.cs. Don’t worry about this file for now as we won’t really be changing anything there. The two files that we will be working with are the Main.storyboard file (for adding the buttons, text labels, and text boxes) and ViewController.cs (for coding the functionality).

ios5

Double-click the Main.storyboard file to open it. It may take a minute to load. The storyboard is where you will add your user interface elements such as buttons, text boxes and text labels. Choose the iPhone device that you want to use as the preview for your storyboard eg. iPhone 6.

ios6

Step 6

In the Toolbox panel (use the search box to find and add the Toolbox to your layout if you don’t see it there), scroll down until you see Label (you can also search in the Toolbox for the Label element.

Drag a Label element on to the phone screen where you would like to place it.

ios7

Step 7

Change the Text value in the Properties panel (on the Widgets tab) to ‘Enter temperature in degrees:’.

ios8

Step 8

Drag the edges of the Label element to resize it so that you can see all of the text.

ios9

You can also change the colour of the text, the font and alignment (eg. align to center) from the Properties panel.

ios10

Step 9

Drag a Text Field element from the Toolbox on to the screen under the text label. Change its Placeholder text to ‘Temperature in degrees’. Resize the Text Field and center-align the text.

ios11

Step 10

Drag two Button elements on to the screen and resize them to fit their text. Change the first button’s text to ‘Convert to Celsius’ and the second button’s text to ‘Convert to Fahrenheit’.

ios12

Step 11

The last element to add is the text label which will display the result of the temperature conversion. Drag a Label element on to the screen and change its default Text to 0, change its Colour and Font size/style. You can also change the Alignment to center.

ios13

Step 12

Now we need to name each of the screen elements so that they can be accessed by the code. Firstly, click on the temperature text field and change its Name to tempTextField.

ios14

Step 13

Now give the ‘Convert to Celsius’ button the Name cButton.

ios15

Also set the Name of the ‘Convert to Fahrenheit’ button to fButton.

ios16

Step 14

Lastly, click on the text label which will display the conversion result and change its Name to resultLabel. Now is a good time to save the Main.storyboard file (Click File > Save).

ios17

Step 15

Now its time to do some coding. Open the ViewController.cs file. In this file, click inside the ViewDidLoad method and add the code highlighted below. This code will add a button touch event that will occur when the user touches to Convert to Celsius button. When we create the cButton.TouchUpInside event it will also automatically create a new method CButton_TouchUpInside which will contain the code that will convert a temperature to Celsius.

ios18

Step 16

We now need to also create a button touch event for the Convert to Fahrenheit button and a method that will contain its code.

ios19

Step 17

Now let’s add the code for the FButton_TouchUpInside method first. This method will be called when the Convert to Fahrenheit button is pressed by the user. Add the highlighted code below. Firstly, a float variable called temp is created to store the temperature value that the user enters into the text field as a float value. Then a variable called fResult will convert the temperature from Celsius to Fahrenheit and store the result as a float value. Lastly, the text on the resultLabel element will display the result and the text ‘degrees Fahrenheit’ at the end of the sentence eg. ’68 degrees Fahrenheit’.

ios20

Note: You may need to resize the fResult label element in the Main.storyboard file so that it can fit the result and text.

Step 18

We can now add the code for the Convert to CButton_TouchUpInside method to run the conversion when the Convert to Celsius button is pressed. Add the highlighted code to this method shown below. Then save your code (File > Save).

ios21

Step 19

Now go back to the Main.storyboard file and select the Text Field element. In the Properties panel and on the Widget tab, scroll down and change the Keyboard Type to Decimal Pad so that numbers with decimal place can be typed in and the most suitable keypad is displayed. Save the file.

ios22

Step 20

At this point, the app will work and will allow the user to type in a temperature (as a whole or decimal number) and convert it to either Celsius or Fahrenheit. However, after the user has typed in a number they should be able to hid the keyboard if it is no longer needed.

Before testing the app we will add a little piece of code that will allow the keypad to be dismissed by the user when it is no longer needed. To do this, go back to the ViewController.cs file and start typing the highlighted line of code (where it is shown below). As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code. This will create a new override method called TouchesBegan. Inside this method we will add some code to dismiss the keyboard.

ios23
As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code.

Add the following code inside the new override method called TouchesBegan to allow the keyboard to be dismissed when typing has been completed by the user. Then save the file.

ios24

Finishing up

All of the coding is done. Congratulations – you have made your first iOS app using Xamarin and the C# programming language! Remember to save your files.Now just select a type of iPhone model you would like to test this app on and click on the Build button to start testing/emulating the app.

ios25

And this is what the completed app should look like…

ios26

What next?

Test your app thoroughly. Are there any problems with your app? Does it crash under some circumstances? Is there any way it could be improved. Jump into the next tutorial to see how this app can be improved.

Sample code

You can download the sample code for the ViewController.cs file here:

using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      cButton.TouchUpInside+= CButton_TouchUpInside;

      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse(tempTextField.Text);
      float fResult = temp * 1.8f + 32f;
      resultLabel.Text = fResult.ToString () + " degrees Fahrenheit";
    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse (tempTextField.Text);
      float cResult = (temp - 32f) / 1.8f;
      resultLabel.Text = cResult.ToString () + " degrees Celsius";
    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}

What is Xamarin?

Welcome to the tutorial series on building mobile apps for Android and iOS with Xamarin and the C# programming language. In this tutorial series you will learn how to use the Xamarin platform to design and develop mobile apps for both major smartphone operating systems – Android and iOS.

Xamarin logo

With Xamarin, you can build native apps without having to know Swift, Objective-C, and Java. Most of the code you write in C# with Xamarin can be used for both Android and iOS, making it much easier to write native apps for both platforms. Xamarin allows you to write native apps for different platforms with native UI, native API access, and native performance using a shared C# codebase, the same IDE, language, and APIs anywhere.

In this tutorial series, we will start by installing and getting to know the Xamarin platform and basics of the C# language, and then we will learn how to make a basic Android and iOS app. The great thing about learning C# is that you will also be able to use that language to develop amazing 2D and 3D games for several platforms in Unity 3D by following the tutorials here.

The next tutorial will show you how to download and install Xamarin for Windows and Mac OS.

Note: CodeMahal is not endorsed by or associated with Xamarin in any way. CodeMahal provides free tutorials on using the Xamarin platform.

Using Adobe Shape CC app to turn sketches into Illustrator drawings

This video tutorial explains how to use the Adobe Shape CC app (on iOS and Android) to take a photo of a hand-drawn sketch and turn it into an SVG vector graphic which can be opened and edited in Adobe Illustrator CC.

Watch the video below or on YouTube.