【发布时间】:2013-12-17 16:01:17
【问题描述】:
我有一个问题,在 iOS7 上右对齐 UITextField 时,当用户键入“空格”时,它不会立即出现。如果我键入另一个字符,则会出现空格。
在 iOS 6 中不会发生
有人知道如何解决这个问题吗?
【问题讨论】:
-
请提供更多细节或您做了什么,以便我们正确理解
标签: ios ios7 uitextfield
我有一个问题,在 iOS7 上右对齐 UITextField 时,当用户键入“空格”时,它不会立即出现。如果我键入另一个字符,则会出现空格。
在 iOS 6 中不会发生
有人知道如何解决这个问题吗?
【问题讨论】:
标签: ios ios7 uitextfield
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location == textField.text.length && [string isEqualToString:@" "]) {
// ignore replacement string and add your own
textField.text = [textField.text stringByAppendingString:@"\u00a0"];
return NO;
}
// for all other cases, proceed with replacement
return YES;
}
从文本中删除代码
self.txtFirstName.text = [self.txtFirstName.text stringByReplacingOccurrencesOfString:@"\u00a0" withString:@" "];
来自这个 stackoverflow 答案 - Right aligned UITextField spacebar does not advance cursor in iOS 7
【讨论】:
我不知道如何解决,但我有一个建议,您可以同时将所有空格替换为非常相似的 unicode 字符(如 U+00A0),然后将它们切换回来已输入字符?
只需在 .h 中包含 <UITextFieldDelegate>,在 viewDidLoad 中设置 UITextField.delegate = self;
然后执行如下操作:
//!!!!!*****!*!*!!!*!*** Make SURE you set the delegate code before doing this (as mentioned in the original SO answer)
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([string isEqualToString:@" "]) {
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@"\u00A0"];//U+00A0 is a unicode character that seems very similar to space but isn't treated as whitespace...
} else {
textField.text = [textField.text stringByReplacingOccurrencesOfString:@"\u00A0" withString:@" "];//switches our u+00A0 unicode character back to a white-space everytime a space is not typed.
}
return (![string isEqualToString:@" "]);//returns YES if it doesn't equal whitespace, else NO (because we did a manual replace)
}
*注意,我还没有机会对此进行测试,因为我不在 xCodeProj 附近。让我知道它是如何工作的 :) 如果有人看到任何错误,请随时进行编辑 O:) 谢谢大家!
【讨论】: