6
注意!這個問題不是this或this問題的重複!這是一個讓問題更清楚的新問題。以正確的方式檢測UITextField中的退格
所以我已經按照上面的帖子的所有說明,我有這UITextField
變成空的,每次用戶點擊返回按鈕時移動到一個新的位置。此外,我跟蹤的TextView的輸入和我的位置TextView的是創建一個文本標籤,就像這樣:
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if (textField.text.length > 5) {
CGRect labelFrame = CGRectMake(textField.frame.origin.x, textField.frame.origin.y, 0, 0);
UILabel *label = [[UILabel alloc] initWithFrame: labelFrame];
label.font = [UIFont fontWithName:@"HelveticaNeue" size:14];
[label setText:textField.text];
[label setTextColor: [BSFunctions getColorFromHex:@"3f3f3f"]];
label.backgroundColor =[UIColor lightGrayColor];
[label sizeToFit];
[labelsArray addObject:label];
[self.view addSubview: label];
CGRect newTextFieldFrame = CGRectMake(labelFrame.origin.x + label.frame.size.width + 5, labelFrame.origin.y, 320, 30);
NSLog(@"Rect is %@", NSStringFromCGRect(newTextFieldFrame));
textField.frame = newTextFieldFrame;
textField.text = @"\u200B";
}
return YES;
}
我設置文本中UITextField
文本是@"\u200B"
,然後我要檢測它的退格鍵是這樣的:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if ([string isEqualToString:@""]) {
NSLog(@"backspace button pressed");
if (labelsArray.count > 0) {
UILabel *labelToDelete = [labelsArray lastObject];
CGRect labelPosition = labelToDelete.frame;
CGRect oldPosition = textField.frame;
textField.frame = CGRectMake(labelPosition.origin.x, labelPosition.origin.y, oldPosition.size.width, oldPosition.size.height);
[labelToDelete removeFromSuperview];
[labelsArray removeLastObject];
textField.text = @"\u200B";
}
}
return YES;
}
但問題是,它只能一次,然後,即使有特殊字符加在它不工作的文本框的開始。什麼可能是錯的? shouldChangeCharactersInRange:replacementString: