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
- Make sure that to show the utility area by clicking on the top right button in xcode.
- 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.
- 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.
- 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
- Once the button is in the window double click on the button and change the text to Record
- 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.
- 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.
- Now drag the button and re-center it in the view by using horizontal and vertical guidelines XCode provides. (Screenshot)
- 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)
- 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.
- Now run the app in the simulator.
- You should see the button but shouldn’t it be centered? We need to fix this next to center the button.
- 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.
- Now let’s fix the button also.
- The best way to find to do this is by trying to find articles on internet by googling.
- 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)
- You should read these articles as they provide detail on the many ways to add constraints to center the button in it’s view.
- 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.
- You should see now a menu select the second option Center Vertically in Container.
- 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
- Now XCode has added constraints to make sure that the button is centered vertically and horizontally.
- 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)
- You should either do step 5-7 or step 8 not both.
- 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.
- 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)
- Now let’s run the app. You should see the button centered in the middle now.
- If you ever want to delete a constraint just select the constraint in document outline and select delete button on your keyboard.
- 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.
- Save this image on your computer. (This image is provided by Udacity swift instructor). We will use this microphone image for the record button.
- Now hide the utilities area for more room.
- In the left navigator window make sure that the first tab is clicked and your files are listed.
- Now click on images.xcassets. This is the way you add images now in XCode.
- There will be two sections. In the left section click on + icon(screenshot) and click on New Image Set. (Screenshot)
- Double click on the microphone entry added and rename it to Mircophone
- Open the directory where you saved the microphone image in finder.
- Now drag the microphone image to xcode Microphone entry 1x.
- Now go back to storyboard and show the utilities area.
- Click on record audio button and from the utilities area empty record button text highlighted here.
- Scroll down and select the Image dropdown and select microphone image.
- Run the simulator and your microphone icon should be there now.
- 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?
- 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.
- 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.
- 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.
- To fix this save this image and drag it to the 2x slot in image assets microphone 2x blank space.
- Now run the app and the image should not be distorted as iPhone is using the correct image.
- 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
- 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.
- 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.
- 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.
- First go to storyboard.
- Next hide the left navigator window, console bottom window and the right utilities area to make room.
- 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.
- 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
- 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.
- 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.
- You should see a popup. First select Action from connection dropdown.
- Next, enter recordAudio in the Name field.
- Now select Type field and select UIButton . That is the type of the element which is sending the event in our case a button.
- Leave other fields. The final output should be similar to this screenshot
- 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.
- Add the following statement in recordAudio function. This will print the text in double quotes in console whenever recordAudio is called.
println("In Record Audio")
- 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.
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.
- First go back to standard editor by clicking the button on the left to the button we used to switch on assistant editor.
- 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.
- Drag the label element to the area beneath the microphone and rename the text to Recording. (Screenshot).
- We can change attributes for the label go to font section in file inspector in utilities and click the T 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.
- Then keep the label selected and go to editor->size to fit content.
- Finally center the label.
- Now run the app and you should see the same problem of alignment that happened with the button. We need to add constraints.
- 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.
- 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.
- Click on the label and go the the attributes inspector in utility area.
- Scroll down to the drawing section and tick the hidden check box. (Screenshot)
- Your label on the view will now be greyed out a little.
- Run the app and the label will not show by default.
- 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.
- Now hide all other windows and turn on assistant editor.
- 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
- When you create the outlet there are few things to note. IBOutlet is similar to IBAction that it tells xcode that is an outlet.
- 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
- 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.
- 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.
recordingLabel.hidden = false
- Now run the app and when you click on the microphone the text in the label should appear.
Adding Stop Button
- 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.
- First download the image for stop button here
- 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.
- Next add a button at the bottom of the screen.
- Blank out the text for the button.
- Next, change the image of the button to the stop button image.
- Center it
- 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.
- Run the app to make sure that the button is aligned properly. Here is a screenshot of the position of the button. (Screenshot)
- Now we need to hide the recording text when the stop button is pressed. Turn on the editor assistant.
- Now control drag from the stop button to the view controller and release to add an action with name stopAction and type UIButton
- Finally add the code below to hide the recording label.
recordingLabel.hidden = true
- 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.
- 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.
- 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