以编程方式关注创建为 AccessoryView 的 UITextView

Programmatically focus on UITextView that is created as an AccessoryView

在我的 iOS 应用程序中,我创建了一个 UIAlert 并向其动态添加了一个 UITextView:

 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

我试图专注于最后一行中的 UITextView,以便在 UIAlertView 出现时打开键盘。但是,键盘没有出现,并且 UITextView 没有获得焦点。

我也试过了

[[tweetAlert valueForKey:@"accessoryView"] becomeFirstResponder];

但我收到错误

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIAlertView 0x1358b3200> valueForUndefinedKey:]: this class is not key value coding-compliant for the key accessoryView.'

知道如何关注动态创建的 UITextView,它作为 accessoryView 嵌入到 UIAlertView 中吗?

一般不建议您修改警报视图的视图层次结构。您应该只使用文本条目 UIAlertView:

UIAlertView *tweetAlert = [[UIAlertView alloc] initWithTitle:@"Compose Tweet"
                                                             message:nil
                                                            delegate:self
                                                   cancelButtonTitle:@"Cancel"
                                                   otherButtonTitles:nil];
tweetAlert.alertViewStyle = UIAlertViewStylePlainTextInput;

可以使用UIAlertViewDelegate方法- (void)didPresentAlertView:(UIAlertView *)alertView让textview成为第一响应者。

- (void)didPresentAlertView:(UIAlertView *)alertView {
    [tweetTextView becomeFirstResponder];
}