无法在UITextField中移动光标

时间:2019-10-16 13:56:43

标签: ios uitextfield uikit

我有一个沼泽标准的UI,在几个子视图中嵌入了一个文本字段。我看到一个问题,即在文本字段中键入内容后,我将无法移动光标,而光标只会不断地移回到输入的开头。

在代码中的任何地方都没有调用任何方法来更改编辑位置,例如setSelectedTextRange或类似的方法。

请原谅Objective-C,这是旧版代码库!

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没有设置器或获取器功能,所以那里没有时髦的东西!

1 个答案:

答案 0 :(得分:2)

这里的答案正是@juanreyesv在评论中指出的! becomeFirstResponder的呼叫已移至viewDidAppear,而不是viewWillAppear,现在可以了!