【问题标题】:UITextField inside UIAlertView: how to select text?UIAlertView 中的 UITextField:如何选择文本?
【发布时间】:2012-11-23 09:41:29
【问题描述】:

我需要显示一个 UIAlertView 要求用户更改一些文本,但大多数时候用户会想要:a)保持文本不变或 b)替换整个文本。在极少数情况下,他只想通过附加或修改来更改文本。

因此,为此我想出了以下代码:

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Name for your item"
                                                    message:nil
                                                   delegate:self
                                          cancelButtonTitle:@"Cancel"
                                          otherButtonTitles:@"Accept", nil];
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField *textField = [alertView textFieldAtIndex:0];
textField.text = @"Some random text";
[alertView show];

UITextRange *textRange = [textField textRangeFromPosition:textField.beginningOfDocument
                                               toPosition:textField.endOfDocument];
[textField setSelectedTextRange:textRange];

这在 iPhone 上运行良好,在显示警报时选择了文本,它按我的预期工作,但在 iPad 上根本没有选择文本。

我是不是做错了什么,这是 iOS 上的一个错误,还是这种行为记录在我没有找到的某个地方?

【问题讨论】:

  • 我会记录文本范围变量以查看它是 0 还是 NULL。
  • @Opsi 您的代码适用于我在 iOS 5 和 iOS 6 下的 iPad 模拟器。您的测试环境是什么?
  • 那很快 ;) 确实,iPad 上的范围似乎为零,但 iPhone 上没有,所以我想是时候去填补一个错误了......谢谢!
  • @Opsi 它在我运行 iOS 6.0.1 的 iPad 3 上也能正常工作。
  • @robmayoff 我在 5.1 上运行它,XCode 4.5.2,我会在 6 上尝试

标签: objective-c ios cocoa-touch


【解决方案1】:
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"name" message:@"" delegate:self
                                            cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];

alertViewt.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField *textField = [Renamealert textFieldAtIndex:0];
textField.text=@"XYZZZ   ";
[alertView show];

UITextRange *textRange = [textField textRangeFromPosition:textField.beginningOfDocument
                                               toPosition:textField.endOfDocument];
[textField setSelectedTextRange:textRange];

【讨论】:

  • 我看不出这个答案对原始问题有什么补充...你能详细说明一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多