无法在 UITextField 中移动光标



我有一个相当沼泽标准的用户界面,在几个子视图中嵌入了一个文本字段。我看到一个问题,一旦我在文本字段中输入,我就无法移动光标,它不断地移回输入的开头。

代码中的任何位置都不会调用任何方法来更改编辑位置,例如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没有二传手或吸气手功能,所以那里没有什么时髦的事情发生!

这里的答案正是@juanreyesv评论中指出的!becomeFirstResponder电话被转移到viewDidAppear而不是viewWillAppear,现在它正在工作!

最新更新