Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

LABS
iPhone on blocks: UITextFields

If you’ve ever used a UITextField in an iPhone project (or, I suppose, an NSTextField in a Cocoa project) you know that you pass it a delegate object in order to respond to events. Handling the “Return” key press from the on-screen keyboard may look something like this (probably implemented in your view controller):

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (0 == [textField.text length]) {
        return NO;
    }
    [self doSomethingWithText:textField.text];
    [textField resignFirstResponder];
    return YES;
}

The delegate pattern is de rigueur for Cocoa classes, so you’ve likely never given this much special thought. Unless, that is, you decided at some point to have two text fields on screen at once. With two text fields you need to handle two sets of callbacks. You have a couple options for how to do this:

  1. Use the same delegate to handle both sets of callbacks, and use conditionals or switch statements to differentiate between the text fields.
  2. Create UITextField subclasses for each text field, each of which knows how to handle its own events. Each subclass will need a reference to the view controller, and you’ll need to expose methods in the view controller’s public interface for the subclasses to call, in order to effect some change in the system.
  3. Create a separate delegate class for each text field. As in the previous option, each delegate class will need a reference to the view controller and a way to send it messages to effect changes in the system.

None of these options feel particularly satisfactory: the second overuses inheritance, which the delegate pattern exists largely to avoid; both the second and third can result in class explosion; and the first feels so… procedural. Isn’t Object Oriented Programming supposed to save us from problems like this?

Procedural or no, Apple suggests the first option in all of their documentation and example code. An if statement isn’t really a big deal for two text fields; but what about three? Five? Ten? Your delegate method could look something like this:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.fooTextField) {
        if (0 == [textField.text length]) {
            return NO;
        }
        // Do something with the text
        }
    } else if (textField == self.barTextField) {
        // different logic...
    } else if (textField == self.batTextField) {
        // more different logic...
    } else if (textField == self.bazTextField) {
        // yet more different logic...
    } else if (textField == self.wibbleTextField) {
        // still yet more different logic...
    } else if ...
    [textField resignFirstResponder];
    return YES;
}

Or, alternately, you could resort to the dreaded switch statement. Either way, ugh.

The fundamental problem here is that only one object (let’s say a view controller) knows what to do when events occur, but only the subordinate objects (the text fields) know when the events occur. Each text field object encapsulates the behavior of its particular on-screen representation, but can’t access the internal state or implementation details of the view controller in order to effect changes to the system.

The recent addition of blocks to iOS can help us work around this problem. Since blocks are closures they capture and maintain their surrounding state at the point they’re instantiated. We can use this to define an implementation, and capture the internal state of our view controller, and pass all of this to an individual text field. Once done, each text field object will manage its own behavior without any intervention from the view controller whatsoever.

To make this work you’d need one (and only one) new class (theoretically, you could make a subclass of UITextField and set it to be its own delegate; unfortunately, setting a UITextField to be its own delegate seems to create an infinite loop deep in the bowels of Cocoa):

@interface BlockTextFieldDelegate : NSObject <UITextFieldDelegate>
@property (nonatomic, copy) BOOL (^textFieldShouldReturn)(UITextField *textField);
@end

@implementation BlockTextFieldDelegate
@synthesize textFieldShouldReturn = textFieldShouldReturn_;

- (void)dealloc {
    self.textFieldShouldReturn = nil;
    [super dealloc];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (self.textFieldShouldReturn) {
        return self.textFieldShouldReturn(textField);
    }
    return YES;
}

@end

Using the BlockTextFieldDelegate class might look like this (in your view controller):

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textFieldDelegate.textFieldShouldReturn = ^ BOOL (UITextField *textField) {
        if (0 == [textField.text length]) {
            return NO;
        }
        [self doSomethingWithText:textField.text];
        [textField resignFirstResponder];
        return YES;
    };
}

The astute reader, armed with a passing familiarity with Apple’s Human Interface Guidelines, will point out that having several text fields on one screen may create a poor user experience. Certainly true for the iPhone, perhaps less true for the iPad’s larger screen. In any case, this technique works for any situation that requires multiple objects, not just UITextFields, reporting to a single delegate. Consider the case of multiple concurrent network requests, created by NSURLConnection objects, managed by a single view controller.

The astute reader will also point out that you may leave off the return type when defining blocks, assuming the compiler can infer it. I left the return type in to keep the example as explicit as possible, but the above block assignment could look like this (note the missing BOOL return declaration):

self.textFieldDelegate.textFieldShouldReturn = ^ (UITextField *textField) {

The block syntax isn’t beautiful, but you can use this technique to eliminate conditional chains, keep the number of classes and subclasses you create low, and avoid exposing the internal state of your objects; and that is beautiful.

Comments
Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *