Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

CHAPTER 3: Handling Basic Interaction

63

Writing the Action Method

So far, we’ve designed our user interface, and wired up both outlets and actions to our user interface. All that’s left to do is to use those actions and outlets to set the text of the label when a button is pressed. You should still be in BIDViewController.m, but if you’re not, single-click that file in the project navigator to open it in the editor. Find the empty buttonPressed: method that Xcode created for us earlier.

In order to differentiate between the two buttons, we’re going to use the sender parameter. We’ll retrieve the title of the button that was pressed using sender, and then create a new string based on that title, and assign that as the label’s text. Add the bold code below to your empty method:

- (IBAction)buttonPressed:(UIButton *)sender {

NSString *title = [sender titleForState:UIControlStateNormal]; statusText.text = [NSString stringWithFormat:@"%@ button pressed.", title];

}

This is pretty straightforward. The first line retrieves the tapped button’s title using sender. Since buttons can have different titles depending on their current state, we use the UIControlStateNormal parameter to specify that we want the title when the button is in its normal, untapped state. This is usually the state you want to specify when asking a control (a button is a type of control) for its title. We’ll look at control states in more detail in Chapter 4.

The next line creates a new string by appending the text “button pressed.” to the title we retrieved in the previous line. So, if the left button, which has a title of Left, is tapped, this line will create a string that says “Left button pressed.” This new string is assigned to the label’s text property, which is how we change the text that the label is displaying.

MESSAGE NESTING

Objective-C messages are often nested by some developers. You may come across code like this in your travels:

statusText.text = [NSString stringWithFormat:@”%@ button pressed.”, [sender titleForState:UIControlStateNormal]];

This one line of code will function exactly the same as the two lines of code that make up our buttonPressed: method. This is because Objective-C methods can be nested, which essentially substitutes the return value from the nested method call.

For the sake of clarity, we won’t generally nest Objective-C messages in the code examples in this book, with the exception of calls to alloc and init, which, by long-standing convention, are almost always nested.

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]