Moving the cursor to the beginning of UITextField

前端 未结 3 1714
深忆病人
深忆病人 2020-11-29 13:17

Is there a way to make the cursor be at the start of a UITextField?

When I display the control with content, the cursor is placed at the end of the string. I\'d lik

3条回答
  •  抹茶落季
    2020-11-29 13:56

    You're fighting the system on this one. UITextField does not have any public properties to set the cursor position (which actually correlates to the beginning of the current selection). If you can use a UITextView instead, the following delegate methods will force the cursor to the beginning of the text. Just be aware that users won't expect this behavior and you should double-check your motives for wanting to do it.

    - (void)textViewDidBeginEditing:(UITextView *)textView {
        shouldMoveCursor = YES;
    }
    
    - (void)textViewDidChangeSelection:(UITextView *)textView {
        if(shouldMoveCursor)
        {
            NSRange beginningRange = NSMakeRange(0, 0);
            NSRange currentRange = [textView selectedRange];
            if(!NSEqualRanges(beginningRange, currentRange))
                [textView setSelectedRange:beginningRange];
            shouldMoveCursor = NO;
        }
    }
    

    Where shouldMoveCursor is a BOOL variable you maintain in your controller.

提交回复
热议问题