0
  1. I setup my UITextfield to be NSTextAlignmentRight ,and it's cursor is at the right end as normal.
    enter image description here

  2. When I entered a space the cursor go to the left end of UITextfield.
    enter image description here

  3. I try to fix this problem by implement UITextFieldDelegate method

like this:

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  if (range.location == 0 && [string isEqualToString:@" "]) {
    return NO;
  }
return YES;
}

But it's a bit of a mess,and I can't input space for the first character.

Is there a better solution to fix this?
Why this bug happens?

Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
wj2061
  • 6,778
  • 3
  • 36
  • 62

1 Answers1

2
- (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

For Ref: Right aligned UITextField spacebar does not advance cursor in iOS 7

Community
  • 1
  • 1
Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38