右对齐的 UITextField 空格键不会在 iOS 7 中前进光标 [英] Right aligned UITextField spacebar does not advance cursor in iOS 7
问题描述
在我的 iPad 应用中,我注意到 iOS 6 和 iOS 7 之间使用 UITextFields 的不同行为.
In my iPad app, I noticed different behavior between iOS 6 and iOS 7 with UITextFields.
我创建 UITextField 如下:
I create the UITextField as follows:
UIButton *theButton = (UIButton*)sender;
UITextField *textField = [[UITextField alloc] initWithFrame:[theButton frame]];
[textField setDelegate:self];
[textField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[textField setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
textField.textAlignment = UITextAlignmentRight;
textField.keyboardType = UIKeyboardTypeDefault;
...
[textField becomeFirstResponder];
在 iOS 6 中,当我键入hello world"时,当我在hello"之后按空格键时,光标会前进一个空格.
In iOS 6, when I type "hello world" the cursor advances a blank space when I hit the spacebar after "hello."
在 iOS 7 中,当我点击空格键时,光标不会前进.但是,当我在world"中输入w"时,它会显示空格和 w.
In iOS 7, the cursor does not advance when I hit the spacebar. However, when I type the "w" in "world," it shows the space and the w.
如何在 iOS 7 中按空格键时移动光标?
How can I advance the cursor when the spacebar is hit in iOS 7?
更新:
如果我将 textField.textAlignment 更改为 UITextAlignmentLeft,则该空间会出现在 iOS 7 中.如果可能,我希望它保持右对齐.
If I change the textField.textAlignment to UITextAlignmentLeft, then the space appears in iOS 7. I would like to keep it right aligned, if possible.
推荐答案
这有点麻烦,但如果你真的需要它来看待 iOS6 的方式,你可以用 非中断空间,如其所写.它被区别对待.示例代码可能如下所示:
It would be a bit of a hack, but if you really need that to look the iOS6 way, you can replace space with non-breaking space as it's written. It's treated differently. Example code could look like this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// only when adding on the end of textfield && it's a space
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;
}
如果不清楚,textField:shouldChangeCharactersInRange:replacementString:
是一个 UITextFieldDelegate
协议方法,所以在你的例子中,上面的方法将在由[textField setDelegate:self]
.
In case it's not clear, textField:shouldChangeCharactersInRange:replacementString:
is a UITextFieldDelegate
protocol method, so in your example, the above method would be in the viewcontroller designated by [textField setDelegate:self]
.
如果您想要恢复常规空格,显然您还需要记住通过将出现的 @"u00a0"
替换为 @" "
来将文本转换回来从文本字段中取出字符串时.
If you want your regular spaces back, you will obviously also need to remember to convert the text back by replacing occurrences of @"u00a0"
with @" "
when getting the string out of the textfield.
这篇关于右对齐的 UITextField 空格键不会在 iOS 7 中前进光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!