我有一个相当标准的 UI,在几个 subview 中嵌入了一个文本字段。我看到一个问题,一旦我在文本字段中输入,我就无法移动光标,它会不断地移回输入的开头。
代码中的任何地方都没有调用任何方法来更改编辑位置,例如 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
没有 setter 或 getter 函数,所以没有什么奇怪的事情发生! 最佳答案
这里的答案正是@juanreyesv 在评论中指出的! becomeFirstResponder
调用已移至 viewDidAppear
而不是 viewWillAppear
,现在它可以工作了!
关于ios - 无法在 UITextField 中移动光标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58415101/