UIAlertView里面的UITextField无法设置游标

时间:2013-10-18 19:14:12

标签: ios uitextfield uialertview

这是我的代码:

    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];

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

2 个答案:

答案 0 :(得分:1)

在您的Controller上实施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>并设置委托,如上所示。

答案 1 :(得分: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];

TextField委托

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