iPhone OS 3.2 UIKeyInput Example

I’ve been experimenting with custom text processing and input in iPhone OS 3.2 and there are very few examples out there on the Internets so I figured I’d throw a few up. If you’re looking to implement a custom view that allows you to edit simple text that’s only a single line then you may want to start with the UIKeyInput protocol. It’s only the starting point as it doesn’t display a cursor or allow your to change the position of the cursor but it does allow you to enter and delete text. An example would look something like the following UIView subclass:

The header:

//
//  EditingView.h
//  TextEditing
//
//  Created by Jeffrey Sambells on 10-04-21.
//  Copyright 2010 TropicalPixels. All rights reserved.
//

#import <UIKit/UIKit.h>


@interface UIKeyInputExampleView : UIView <UIKeyInput> {
	NSMutableString *textStore;
}

@property (nonatomic, retain) NSMutableString *textStore;

@end

and the implementation:

//
//  EditingView.m
//  TextEditing
//
//  Created by Jeffrey Sambells on 10-04-21.
//  Copyright 2010 TropicalPixels. All rights reserved.
//

#import "UIKeyInputExampleView.h"

@implementation UIKeyInputExampleView

@synthesize textStore;

- (id)initWithFrame:(CGRect)frame {
	if ((self = [super initWithFrame:frame])) {
		// Initialization code
		self.textStore = [NSMutableString string];
		[self.textStore appendString:@"Touch screen to edit."];

		self.backgroundColor = [UIColor whiteColor];
	}
	return self;
}

- (void)dealloc {
	[textStore dealloc];
	[super dealloc];
}

#pragma mark -
#pragma mark Respond to touch and become first responder.

- (BOOL)canBecomeFirstResponder { return YES; }

-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
	[self becomeFirstResponder];
} 

#pragma mark -
#pragma mark Drawing

- (void)drawRect:(CGRect)rect {
	CGRect rectForText = CGRectInset(rect, 20.0, 20.0);
	UIRectFrame(rect);
	[self.textStore drawInRect:rectForText withFont:[UIFont fontWithName:@"Helvetica" size:24.0f]];
}

#pragma mark -
#pragma mark UIKeyInput Protocol Methods

- (BOOL)hasText {
	if (textStore.length > 0) {
		return YES;
	}
	return NO;
}

- (void)insertText:(NSString *)theText {
	[self.textStore appendString:theText];
	[self setNeedsDisplay];
}

- (void)deleteBackward {
	NSRange theRange = NSMakeRange(self.textStore.length-1, 1);
	[self.textStore deleteCharactersInRange:theRange];
	[self setNeedsDisplay];
}

@end

If you display the view and touch it, the keyboard will pop up and allow you to append and delete text. If you want to experiment you can download a working project from my GitHub account

Neat.