Format UITextField text without having cursor move to the end

后端 未结 6 1434
借酒劲吻你
借酒劲吻你 2020-12-23 17:21

I am trying to apply NSAttributedString styles to a UITextField after processing a new text entry, keystroke by keystroke. The problem is t

6条回答
  •  生来不讨喜
    2020-12-23 17:49

    The way to make this work is to grab the location of the cursor, update the field contents, and then replace the cursor to its original position. I'm not sure of the exact equivalent in Swift, but the following is how I would do it in Obj-C.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        UITextPosition *beginning = textField.beginningOfDocument;
        UITextPosition *cursorLocation = [textField positionFromPosition:beginning offset:(range.location + string.length)];
    
        textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
        /* MAKE YOUR CHANGES TO THE FIELD CONTENTS AS NEEDED HERE */
    
        // cursorLocation will be (null) if you're inputting text at the end of the string
        // if already at the end, no need to change location as it will default to end anyway
        if(cursorLocation)
        {
            // set start/end location to same spot so that nothing is highlighted
            [textField setSelectedTextRange:[textField textRangeFromPosition:cursorLocation toPosition:cursorLocation]];
        }
    
        return NO;
    }
    

提交回复
热议问题