Right aligned UITextField spacebar does not advance cursor in iOS 7

前端 未结 14 1680
执笔经年
执笔经年 2020-12-07 23:04

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

I create the UITextField as follows:

UIButton *theButton = (U         


        
14条回答
  •  离开以前
    2020-12-07 23:24

    My following solution also takes care of the problem with the cursor jumping to the end when typing a space in the middle or beginning of the string. Also pasting a string is now processed correctly too.

    I also put in a check for email address fields and other checks, but the interesting part is the last part. It works perfectly for me, have yet to find a problem with it.

    You can directly copy/paste this in your project. Don't forget to implement the didBeginEditing and didEndEditing to replace the spaces with non-breaking spaces and back!

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        if (textField.textAlignment != NSTextAlignmentRight) //the whole issue only applies to right aligned text
            return YES;
    
        if (!([string isEqualToString:@" "] || string.length > 1)) //string needs to be a space or paste action (>1) to get special treatment
            return YES;
    
        if (textField.keyboardType == UIKeyboardTypeEmailAddress) //keep out spaces from email address field
        {
            if (string.length == 1)
                return NO;
            //remove spaces and nonbreaking spaces from paste action in email field:
            string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];
        }
    
        //special treatment starts here
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@"\u00a0"];
        UITextPosition *beginning = textField.beginningOfDocument;
        textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
        UITextPosition *start = [textField positionFromPosition:beginning offset:range.location+string.length];
        UITextPosition *end = [textField positionFromPosition:start offset:range.length];
        UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end];
        [textField setSelectedTextRange:textRange];
    
        return NO;
    }
    

提交回复
热议问题