Ada*_*Woś 50
设置autocapitalizationType
于UITextAutocapitalizationTypeAllCharacters
上UITextField
.
有关更多详细信息,请参阅UITextInputTraits协议(由UITextField采用).
Mon*_*art 36
这种解决方案并不完全令人满意.
即使autocapitalizationType
设置为UITextAutocapitalizationTypeAllCharacters
,用户仍然可以按下盖子以释放大写锁定.并且textField.text = [textField.text stringByReplacingCharactersInRange:range withString:[string uppercaseString]]; return NO;
解决方案并不是那么好:如果用户编辑文本的中间部分(在textField.text =
编辑光标到达字符串的末尾之后),我们就会松开编辑点.
我已经完成了两个解决方案的混合,这就是我的建议:设置UITextAutocapitalizationTypeAllCharacters
,并将以下代码添加到委托UITextField
.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
// Check if the added string contains lowercase characters.
// If so, those characters are replaced by uppercase characters.
// But this has the effect of losing the editing point
// (only when trying to edit with lowercase characters),
// because the text of the UITextField is modified.
// That is why we only replace the text when this is really needed.
NSRange lowercaseCharRange;
lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];
if (lowercaseCharRange.location != NSNotFound) {
textField.text = [textField.text stringByReplacingCharactersInRange:range
withString:[string uppercaseString]];
return NO;
}
return YES;
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ser 31
虽然所有其他答案确实有效(它们使输入为大写),但它们都存在不保留光标位置的问题(尝试在现有文本的中间插入一个字符).这显然是发生在的二传手UITextField
s"的text
属性,我还没有找到一种以编程方式恢复它(例如,恢复原来selectedTextRange
不工作).
不过,好消息是,有一个直接的方式来更换的零件UITextField
的(或UITextView
的)文本,不从这个问题遭受:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// not so easy to get an UITextRange from an NSRange...
// thanks to Nicolas Bachschmidt (see http://stackoverflow.com/questions/9126709/create-uitextrange-from-nsrange)
UITextPosition *beginning = textField.beginningOfDocument;
UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
UITextPosition *end = [textField positionFromPosition:start offset:range.length];
UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end];
// replace the text in the range with the upper case version of the replacement string
[textField replaceRange:textRange withText:[string uppercaseString]];
// don't change the characters automatically
return NO;
}
Run Code Online (Sandbox Code Playgroud)
有关这些方法的更多信息,请参阅文档UITextInput
.