iOS Development With Swift Part 3

This is part 3 of the swift iOS Programming series. You should read part 1 and part 2 before attempting this tutorial. This course is based on Udacity swift programming course and it is basically a text version of the videos present in Udacity. Last time we had just started exploring Xcode not let’s jump and start building the UI and the code needed for our app. I am only a student of Udacity and completed this course as a student and writing this to help others stuck in iOS development in Udacity and clear up my concepts.

Adding UI Buttons

  1.  Make sure that to show the utility area by clicking on the top right button in xcode.
  2. Once you are in utility area you will see two sections. The first section contains will be empty by default and contains different tabs contents related to current selected item. The bottom section of utility area is what we are interested in.
  3. In the bottom section for utility area you will see many UI elements like view controller, navigation controller etc. Scroll down to find the button UI element.
  4. Now drag the button from the utility area to your view(the white iPhone size window) and try to center it in your view by using the guidelines XCode provide. You will see blue horizontal line when you center the button horizontally in middle of view and another blue vertical line. The button will be centered when the middle of the button is in the middle of the view and you see 2 blue guidelines
  5. Once the button is in the window double click on the button and change the text to Record
  6. Keep the button selected and go to editor menu on top of XCode. Click on Size to Fit Content option this will make sure that if you change the text in the button then the container for button will adjust it’s sized accordingly automatically.
  7. Try changing the text of button by double clicking on it to Record Audio and you will see that the button will adjust it’s size based on the text.
  8. Now drag the button and re-center it in the view by using horizontal and vertical guidelines XCode provides. (Screenshot)
  9. There are more than one way to change properties. Keep the button selected and in the utilities click the 4th tab. This is the attributes inspector. You can change text from here also by changing the field beneath Title. (Screenshot)
  10. On the right of play and stop buttons for simulator you will see your app name and iPhone(Screenshot). Click on the iPhone button and select iPhone 5s. You can select any other device which fits your screen from list of iPhones.
  11. Now run the app in the simulator.
  12. You should see the button but shouldn’t it be centered? We need to fix this next to center the button.
  13. Also, it is possible that the simulator window will not fit your computer screen based. If that happens go to Window menu and click on Scale and select 50% or any other value which makes the simulator fit your screen.
  14. Now let’s fix the button also.

Constraints

  1. The best way to find to do this is by trying to find articles on internet by googling.
  2. If you are stuck google Center align button horizontally and vertically iPhone app and you should find these two articles on appcoda and stackoverflow(Stackoverflow is a great resources for finding how to do something in xcode). (This hint and articles were provided by Udacity instructor)
  3. You should read these articles as they provide detail on the many ways to add constraints to center the button in it’s view.
  4. Have a look at this gif by appcoda which gives a way to center the button. Basically make sure that the button is selected. Now press and hold the control key on your keyboard and hover over the button with mouse and first go horizontally outside the button and you should a blue horizontal line extending from the button outwards. Release the mouse button and ctrl key.
  5. You should see now a menu select the second option Center Vertically in Container.
  6. Now again press the control keys and this time from the button drag the mouse upwards and release and select the option Center Horizontally in Container
  7. Now XCode has added constraints to make sure that the button is centered vertically and horizontally.
  8. Another alternative way to add constrains that appcoda shows is beneath the view window you should a see bar(this is the same bar we used to change the size of our view) and on the right you will see a Align button click on it and tick on checkmarks besides Horizontal Center in Container and Vertical Center in Container. Once you do that your button should be centered. (Screenshot)
  9. You should either do step 5-7 or step 8 not both.
  10. Before we run the app let’s see the constraints in Document Outline. Have a look at the bottom bar where we just clicked on the Align button in step 8. On the left you should see a icon like this. Click on this and document outline should open.
  11. You should see constrains beneath record audio button. Open that and you should see 2 constrains(Screenshot). Click on one by one and the view will be updates to show the constrains. Also, have a look at the utilities window when you click on the constrains and you should more constraint information.(Screenshot)
  12. Now let’s run the app. You should see the button centered in the middle now.
  13. If you ever want to delete a constraint just select the constraint in document outline and select delete button on your keyboard.
  14. Now think how you would explain to someone how the constrains work and discuss on udacity swift forums here

Adding Image to Button

You have added text to button but what we really want is to have an image for the record button instead of text. Let’s do this now.

  1. Save this image on your computer. (This image is provided by Udacity swift instructor). We will use this microphone image for the record button.
  2. Now hide the utilities area for more room.
  3. In the left navigator window make sure that the first tab is clicked and your files are listed.
  4. Now click on images.xcassets. This is the way you add images now in XCode.
  5. There will be two sections. In the left section click on + icon(screenshot) and click on New Image Set. (Screenshot)
  6. Double click on the microphone entry added and rename it to Mircophone
  7. Open the directory where you saved the microphone image in finder.
  8. Now drag the microphone image to xcode Microphone entry 1x.
  9. Now go back to storyboard and show the utilities area.
  10. Click on record audio button and from the utilities area empty record button text highlighted here.
  11. Scroll down and select the Image dropdown and select microphone image.
  12. Run the simulator and your microphone icon should be there now.

Scale Factor

  1. By default you will not be able to find anything wrong with the image but now go to simulator window menu and scale to 100% and look at the microphone image now. You will notice that the image is distorted. Why is that?
  2. This is because different versions of iPhone have different scale factor i.e. number of pixels. Older devices use 1x images. Then retina phone were introduced which had double the width and double the height in terms of pixels and hence the 2x scale factor. Now newer devices have 3x scale factor so 3 times the width and 3 times the height of the original iPhones.
  3. You can read more about this by looking at these resources provided by Udacity The Curious Case of iPhone 6+ 1080p Display and iPhone 6 Screens Demystified. Be sure to watch the video on Udacity for Lesson 2: Video 6 Fixing the Fuzzy Images in XCode for more clearer explanation than what i have provided.
  4. So when we provide only 1x image(100 x 100) xcode tries to stretch the image for 2x(200 x 200) and 3x(300 x 300) and that is why the image is distorted.
  5. To fix this save this image and drag it to the 2x slot in image assets microphone 2x blank space.
  6. Now run the app and the image should not be distorted as iPhone is using the correct image.

Vector Images

  1. Right now we had to provide 1x and 2x versions of the images so appropriate images are used based on device so images are not distorted but we can save use something called Vector Images
  2. You should read how to use vector images in this link. Basically, in simple words you actually produce 1x version of the image and save it in .pdf format.
  3. Next, you create a new image set and tell XCode to use vector images and xcode automatically generates 2x and 3x versions from the 1x pdf format of the image.
  4. This way you save time by only producing 1x version of the image and letting xcode create 2x and 3x on itself.

Adding Action To Button

We have added a microphone button but you will notice nothing happens when you click on the button. That is because you need to link the button with an action in code and write the code to tell xcode what should happen when you click the button. Let’s start with this.

  1. First go to storyboard.
  2. Next hide the left navigator window, console bottom window and the right utilities area to make room.
  3. Next click on the two circles i.e. the second icon in the top right bar(Screenshot). Clicking on the assistant editor button will open up a new window on the right.
  4. Now click on your view window on the left and on the right you should see the controller class in code. When in storyboard you click on a view controller in assistant editor mode Xcode will open the corresponding class. In this case the class of the view in the left is ViewController.swift
  5. Now we need to connect the button on our view in the left to our code in the right by using actions so every time someone clicks on the button a function can be called in our code.
  6. First click on the button in your view and hold down the control key originating from your button and drop the blue line in the window to the right before and after any function. Xcode will try to help when you move the mouse in your file and when you see text appearing Insert Outlet, Action, or Outlet Collection release the mouse and keyboard.
  7. You should see a popup. First select Action from connection dropdown.
  8. Next, enter recordAudio in the Name field.
  9. Now select Type field and select UIButton . That is the type of the element which is sending the event in our case a button.
  10. Leave other fields. The final output should be similar to this screenshot
  11. Now click connect and a function should be created. IBAction before the function tells XCode that this is an action that needs to be connected with storyboard. If you hover over the closed circle on the left gutter to the function as shown in this screenshot you should see that Xcode highlights the button on the left view. This means that this action is connected to the UIButton on the view. If the circle was not filled then that would have meant that IBAction right now is not connected to anything.
  12. Add the following statement in recordAudio function. This will print the text in double quotes in console whenever recordAudio is called.
    1
    
    println("In Record Audio")
  13. Now run the app. When your app runs make sure your console is showing click on the button with bottom bar on the top right on the menu bar. Now click the microphone in the simulator and in the console window you should see the text In Record Audio. This means our function is working as expected.

Adding Label

We need to show the text Recording In Progress somewhere beneath the microphone image when someone clicks on it. Let’s add a text label now.

  1. First go back to standard editor by clicking the button on the left to the button we used to switch on assistant editor.
  2. Open up utilities and from the same area on utilities in bottom section from which we dragged the button we next to drag the Label element onto the view.
  3. Drag the label element to the area beneath the microphone and rename the text to Recording. (Screenshot).
  4. We can change attributes for the label go to font section in file inspector in utilities and click the icon to change the font. From the font dropdown select Custom. Select any other font family from dropdown like to Helti SC. Increase the font size a little to maybe 21.
  5. Then keep the label selected and go to editor->size to fit content.
  6. Finally center the label.
  7. Now run the app and you should see the same problem of alignment that happened with the button. We need to add constraints.
  8. First click on the label and hold down control key and move the mouse down and release and select the Center horizontally in container option.
  9. Again press down the control key and this time mouse the mouse up and drop it on the button and select vertical spacing. Now run the app and the label should be in correct position.

Show Text On Click Only/Outlets

We don’t want the label to show up when the app starts only when the recording button is clicked. So let’s fix that.

  1. Click on the label and go the the attributes inspector in utility area.
  2. Scroll down to the drawing section and tick the hidden check box. (Screenshot)
  3. Your label on the view will now be greyed out a little.
  4. Run the app and the label will not show by default.
  5. That is done but how do we show the label when microphone button is clicked. That’s where outlet comes in. Outlet is a that we can reference a UI element like a button or label through code and get information or change attributes for a visual element by code.
  6. Now hide all other windows and turn on assistant editor.
  7. Drag by holding down control key from the label to code and drop when text Insert Outlet appears.  Give the name to outlet like recordingLabel
  8. When you create the outlet there are few things to note. IBOutlet is similar to IBAction that it tells xcode that is an outlet.
  9. Another point to note is the word weak. Weak refers to the storage used for the outlet. You can think of weak as that you are pointing to something someone else owns. You can keep pointing the object until the owner keeps the object. As soon as the owner throws away the object you are pointing to something which is invalid and not the object you were referring. Oppose to weak there is strong storage which means as long someone as have a reference to an object we can be sure that the items is valid. There has to be at least one person pointing to the object. The object is only destroyed when the last person pointing to the object stops pointing to it and then the object is destroyed. As we have not created the label outlet and we are only referring to something someone else made we need only a weak reference. More detail can be seen here
  10. Lastly, there is ! at the end. This means this is a unwrapped optional. In swift an object must have a value and value cannot be nil if nothing is in the object. That’s when optionals come in. You can read more about optionals here.
  11. Now go to the recordAudio function and add the following code. This code basically says that sets the hidden property of the label to false i.e. to make it visible.
    1
    
    recordingLabel.hidden = false
  12. Now run the app and when you click on the microphone the text in the label should appear.

Adding Stop Button

  1. Let’s add the stop button at the bottom of the screen so that we can stop the recording. The stop button should hide the recording label.
  2. First download the image for stop button here
  3. Next add an image set for the stop button like we did for microphone button in assets and drag the stop button to the 2x slot for stop button. Rename it stop.
  4. Next add a button at the bottom  of the screen.
  5. Blank out the text for the button.
  6. Next, change the image of the button to the stop button image.
  7. Center it
  8. Add constrains to position it. By using control key and dragging to the top set the Center Horizontally In Container option. Next, using control key drag to the bottom of the view and select Bottom space to bottom guide.
  9. Run the app to make sure that the button is aligned properly. Here is a screenshot of the position of the button. (Screenshot)
  10. Now we need to hide the recording text when the stop button is pressed. Turn on the editor assistant.
  11. Now control drag from the stop button to the view controller and release to add an action with name stopAction and type UIButton
  12. Finally add the code below to hide the recording label.
    1
    
    recordingLabel.hidden = true
  13. Run the app and click on the record button first and recording text should appear. Next click on the stop button and the recording label should be hidden now.
  14. Finally let’s change the background of our view. Open up the standard editor and unhide utilities editor. Now open up the Document outline and select view from the document outline.
  15. Go to the utilities editor attributes inspector and change the background dropdown to a color you want. Now run the app and the background of the app should be changed.

That is for this tutorial. In the next tutorial we will start working on changing the scene of our app to another view which will contain the buttons to slow down, and speed up the audio. Also, make the sound like chipmunk or darth vader.

The next part of the tutorials in this series is here

Leave a Reply

Your email address will not be published. Required fields are marked *