simonthumper
simonthumper

Reputation: 1844

Can't move cursor in UITextField

I have a fairly bog-standard UI with a text field embedded in a few subviews. I'm seeing an issue where I can't move the cursor once I've typed in the text field, it continually just moves back to the start of the input.

At no point anywhere in the code are any methods called to change the editing position, like setSelectedTextRange or similar.

Please excuse the Objective-C, this is a legacy codebase!

self.textField = [UITextField new];
self.textField.text = element.value;
self.textField.placeholder = element.placeholder;
self.textField.returnKeyType = UIReturnKeyNext;
self.textField.delegate = self;
self.textField.autocorrectionType = element.autocorrectionType;
self.textField.autocapitalizationType = element.autocapitalizationType;
self.textField.secureTextEntry = element.secureTextEntry;
self.textField.keyboardType = element.keyboardType;
[self.textField addTarget:self action:@selector(handleTextChange:) forControlEvents:UIControlEventEditingChanged];
[self addSubview:self.textField];
- (void)handleTextChange:(UITextField *)sender
{
    self.inputElement.value = sender.text;

    // If we're showing the validation warning, give real time feedback to user
    if (self.isShowingValidationWarning) {
        [self validate];
    }
}

- (void)validate
{
    BOOL isValid = self.inputElement.isValid;

    [self showValidationHint:!isValid animated:YES];
}

- (void)showValidationHint:(BOOL)show animated:(BOOL)animated
{
    self.isShowingValidationWarning = show;

    CGFloat duration = 0.0;

    if (animated) {
        duration = 0.2;
    }

    [UIView animateWithDuration:duration animations:^{

        if (show) {

            self.characterCountLabel.alpha = 0.0;
            self.validationButton.alpha = 1.0;
            self.validationButton.transform = CGAffineTransformMakeScale(1.0, 1.0);
        } else {

            self.characterCountLabel.alpha = 1.0;
            self.validationButton.alpha = 0.0;
            self.validationButton.transform = CGAffineTransformMakeScale(0.1, 0.1);
        }
    }];
}

inputElement.value doesn't have a setter or getter function, so nothing funky going on there!

Upvotes: 3

Views: 993

Answers (1)

simonthumper
simonthumper

Reputation: 1844

The answer here was exactly what @juanreyesv pointed out in the comments! becomeFirstResponder call was moved to viewDidAppear rather than viewWillAppear and now it's working!

Upvotes: 4

Related Questions