Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

objective c - Right aligned UITextField spacebar does not advance cursor in iOS 7

In my iPad app, I noticed different behavior between iOS 6 and iOS 7 with UITextFields.

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];

In iOS 6, when I type "hello world" the cursor advances a blank space when I hit the spacebar after "hello."

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.

How can I advance the cursor when the spacebar is hit in iOS 7?

Update:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

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].

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...