1

这是我的代码:

    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Confirm Address" message:@"Please confirm your address:" delegate:self cancelButtonTitle:@"Confirm" otherButtonTitles:nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField * alertTextField = [alert textFieldAtIndex:0];
    alertTextField.text = @"1234 ABC Street";
    [alertTextField becomeFirstResponder];
    UITextPosition *beginning = [alertTextField beginningOfDocument];
    [alertTextField setSelectedTextRange: [alertTextField
                                   textRangeFromPosition:beginning
                                   toPosition:beginning]];

    [alert show];

光标未设置到文本字段的开头。我究竟做错了什么?

4

2 回答 2

1

UITextFieldDelegate在您的控制器上实现,并将您的setSelectedTextRange代码移动到textFieldDidBeginEditing委托回调:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Confirm Address" message:@"Please confirm your address:" delegate:self cancelButtonTitle:@"Confirm" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.text = @"1234 ABC Street";
[alertTextField becomeFirstResponder];

// Your UITextFieldDelegate implementer here
[alertTextField setDelegate:self];

[alert show];

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    UITextPosition *beginning = [textField beginningOfDocument];
    [textField setSelectedTextRange:[textField textRangeFromPosition:beginning
                                                          toPosition:beginning]];
}

在头文件或类扩展中指定您实现<UITextFieldDelegate>并设置委托,如上所示,这一点很重要。

于 2013-10-18T19:37:59.343 回答
0

将 alertTextField 的委托设置为当前视图控制器,并在 textFields 委托方法中执行设置范围。

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Confirm Address" message:@"Please confirm your address:" delegate:self cancelButtonTitle:@"Confirm" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField *alertTextField = [alert textFieldAtIndex:0];
alertTextField.text = @"1234 ABC Street";
alertTextField.delegate = self;
[alertTextField becomeFirstResponder];
[alert show];

文本字段委托

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    UITextPosition *beginning = [textField beginningOfDocument];
    [textField setSelectedTextRange:[textField
                                     textRangeFromPosition:beginning
                                     toPosition:beginning]];
于 2018-04-30T07:48:20.633 回答