4. Add a Button & Editable Text Field

Next we will add a button to our program.  To make this button do something we will also add a text field that is tied to an array.  When you click on the button the text field will show “Hello World” in 3 different languages.  We will also make this text field editable so you can enter your own text as well, this edited text goes away after you push the button again.

Button & Editable Text Field

Lets start by going to the .xib file we named DOViewController_iPhone.xib.  On the bottom right pane named “Objects” you’ll see an option to add a Round Rect Button, click and drag on this into the iPhone view:

After the button has been added lets give it a title.  To do so click on the pane above the button and you will see a section to add a title to our button, here we call it “Press Me”:

Next we are going to add a text box to display our hello world messages and also make it so we can type our own message as well.  To do this click on the Text field option on the bottom right “Objects” pane, and again drag the field onto our iPhone screen:

After we bring this in we’ll go to split screen so we can see the GUI and the .h file at the same time.  By control clicking and dragging we bring in the connections for both the text field and the button.  To make this work we need create to IBOutlets, so we can get properties of both the button and the text field in the code, we also need to make an IBAction so we can make something happen when we click on the button:

Now we are ready to add the code to make this all work.

First lets add our array to our application, we’ll just make this array when the app launches in out init function.  In this code we make the array with 3 different strings:

These strings will be shown within our text box when we press the button we labeled “Press Me”.  To make he button work we need to edit the code in our action method. To do this we make a counter and just loop through the list, going back to the beginning when we are at the end by using the % (mod function) on our array.  Lastly we just update the text from our returned value based on the array index:

Testing this out we can see that the user pressed the button a couple of times and the text fields is getting updated with each press:

Because we entered this as a text field it all we have to do is make sure it is enables and when we click on the text we can enter any custom text we wish.  Here we can see the user entering Goodbye World, which wasn’t an option in the array:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s