This morning I was looking over some old code I found somewhere (and used in an app) that hacks a UIAlertView in order to get one string of input from the user. It’s overkill for the purpose and looks rather silly but I’ve never seen a simpler way. I then came up with the following approach, which seems to work (iPad 5.1.1 and simulator).
My question is a bit open-ended but, essentially, are there conditions under which this breaks as a strategy: create an off-screen text field with an accessory view, put a proxy text field in the accessory view, and forward various property settings to the proxy?
PMKeyboardTextField.h:
#import <UIKit/UIKit.h>
@interface PMKeyboardTextField : UITextField
- (id)initWithPrompt:(NSString *)prompt;
@end
PMKeyboardTextField.m:
#import "PMKeyboardTextField.h"
@interface PMKeyboardTextField ()
@property (nonatomic, strong) UITextField *inputField;
@end
@implementation PMKeyboardTextField
@synthesize inputField = _inputField;
- (id)initWithPrompt:(NSString *)prompt {
self = [super initWithFrame:CGRectMake(-1, -1, 1, 1)];
if (self) {
UIView *accessory = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 72)];
[accessory setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.8]];
UILabel *getLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, 284, 21)];
[getLabel setBackgroundColor:[UIColor clearColor]];
getLabel.text = prompt;
[accessory addSubview:getLabel];
self.inputField = [[UITextField alloc] initWithFrame:CGRectMake(18, 37, 264, 31)];
[accessory addSubview:self.inputField];
self.inputAccessoryView = accessory;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow)
name:UIKeyboardDidShowNotification
object:nil];
}
return self;
}
- (void)keyboardDidShow {
[self.inputField becomeFirstResponder];
}
- (id<UITextFieldDelegate>)delegate {
return self.inputField.delegate;
}
- (void)setDelegate:(id<UITextFieldDelegate>)delegate {
self.inputField.delegate = delegate;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
As much as I like this idea for its ability to avoid the excess clutter of an alert view or the need to reposition on-screen views, the fatal flaw was pointed out to me in another forum: some people use external keyboards!