问题描述
在iOS 6中,如果您将文字输入到安全文字栏位中,请变更为其他文字栏位,然后返回安全文字栏位并退回,所有字元都会被移除。我很高兴与这种情况发生,但是,我试图启用/禁用基于此安全文本字段中是否有字符的按钮。我知道如何确定字段中的字符,如果退格命中,但我无法确定如何清除所有的字符发生。
In iOS 6 if you type text into a secure text field, change to another text field, then come back to the secure text field and hit backspace, all of the characters are removed. I am fine with this happening, however, I am trying to enable/disable a button based on if this secure text field has characters in it or not. I know how to determine what characters are in the fields and if a backspace is hit but I am having trouble determining how to detect if clearing of all the characters is happening.
这是我使用的委托方法来获取字段的新文本,但是,我似乎不知道如何获取新文本(假设新文本将只是一个空白字符串)如果退格是
This is the delegate method I'm using to get the new text of a field, but, I can't seem to figure out how to get the new text (assuming the new text would just be a blank string) if a backspace is hit that clears all the characters.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//returns the "new text" of the field
NSString * text = [textField.text stringByReplacingCharactersInRange:range withString:string];
}
任何帮助都非常感激。
谢谢!
推荐答案
我使用这个解决方案。
I use this solution. It does not need local variables and sets the cursor position correctly, after deleting the char.
这是这个解决方案的混搭:
It's a mashup of this solutions:
- Backspace functionality in iOS 6 & iOS 5 for UITextfield with 'secure' attribute
- how to move cursor in UITextField after setting its value
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location > 0 && range.length == 1 && string.length == 0)
{
// Stores cursor position
UITextPosition *beginning = textField.beginningOfDocument;
UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
NSInteger cursorOffset = [textField offsetFromPosition:beginning toPosition:start] + string.length;
// Save the current text, in case iOS deletes the whole text
NSString *text = textField.text;
// Trigger deletion
[textField deleteBackward];
// iOS deleted the entire string
if (textField.text.length != text.length - 1)
{
textField.text = [text stringByReplacingCharactersInRange:range withString:string];
// Update cursor position
UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorOffset];
UITextRange *newSelectedRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
[textField setSelectedTextRange:newSelectedRange];
}
return NO;
}
return YES;
}
这篇关于iOS 6 UITextField Secure - 如何检测退格清除所有字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!