In my iOS app, I create a UIAlert and add a UITextView to it dynamically:
UIAlertView *tweetAlert = [[UIAlertView alloc] initWithTitle:@"Compose Tweet"
message:nil
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:nil];
tweetTextView = [UITextView new];
[tweetTextView setText:[NSString stringWithFormat:@"%@ %@", [[NSUserDefaults standardUserDefaults] valueForKey:@"tweetText"], self.setShareURL]];
[tweetAlert setValue:tweetTextView forKey:@"accessoryView"];
[tweetAlert addButtonWithTitle:@"Tweet"];
[tweetAlert show];
[tweetTextView becomeFirstResponder]; // focus textview and open keyboard
I attempt to focus on the UITextView in the last line so that the keyboard is open when the UIAlertView appears. However, the keyboard does not appear, and the UITextView is not in focus.
I also tried
[[tweetAlert valueForKey:@"accessoryView"] becomeFirstResponder];
But I get the error
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIAlertView 0x1358b3200> valueForUndefinedKey:]: this class is not key value coding-compliant for the key accessoryView.'
Any idea how to focus on the dynamically created UITextView, which is embedded as an accessoryView in a UIAlertView?
You can use the UIAlertViewDelegate
method - (void)didPresentAlertView:(UIAlertView *)alertView
to make the textview become first responder.
- (void)didPresentAlertView:(UIAlertView *)alertView {
[tweetTextView becomeFirstResponder];
}