Building my first iOS app with Swift 2.0: Session IV
After three sessions, I am now getting to the fun part. I will be creating the data model first and then connecting it into the view so that I can add and show non-static data.
I will keep the Idea model simple. There is an Idea.title and an Idea.Detail. To access the object instances, I will need AddIdea(), DeleteIdea() and GetIdea() methods that are handled by something called a IdeaManager.
Now, we can connect these models to the view. I’ll do this in three parts in this session:
- Showing and hiding the keyboard
- Updating the button states
Showing and hiding the keyboard
Novice-tip: In your simulator, I needed to uncheck ‘Connect Hardware Keyboard’ to have the keyboard on the simulated phone show up when testing.
I need to do a couple of things:
- Make sure that when in the title UITextField, the keyboard is showing, the ‘Return Key’ is ‘Done’. I have to link and add a method that hides the keyboard when done is clicked. resignFirstResponder() is what hides the keyboard.
- For the larger UITextView for the ‘detail’ input for an Idea, I need to add a ‘Done’ button to the top navigation and then link it to a method that hides the keyboard when the ‘Done’ button is clicked.
Now, let’s make the buttons have state.
For the ‘Done’ button, I want to disable it until there is text in the UITextView for the detailContent. And I want to disable the ‘Add’ button until there is text in the UITextFiled and the UITextView.
So, I did a couple of things:
- Added a handleButtonStates() method that enables and disables the buttons depending on what’s in the input fields.
- Added an “observer” that observed the UITextField (titleText) and the UITextView (detailContent) and called handleButtonStates() to do it’s thing.
Now let’s see if we can save these text fields.
Side-note: I had to re-write the Idea and IdeaManager classes again as I might have dropped the local stashed changes on my dev system. Not important, but having the code described above helped me rewrite that code very quickly.
To save the text fields I did a few things:
- Added an array of Idea elements in IdeaManager
- Refactored the code so that everywhere I was using the simple ‘String’ variable for storing the title, now I am using the Idea class.
- Added an addButton_click() method that calls IdeaManager.AddIdea() and clears the text fields.
- In the main ViewController, updated the tableView method to use the ideas array from the IdeaManager