Can I select a specific block of text in a UITextField?

前端 未结 7 1160
盖世英雄少女心
盖世英雄少女心 2020-11-28 13:43

I have a UITextField in my iPhone app. I know how to make the text field select all of its text, but how can change the selection? Say I wanted to select the last 5 characte

7条回答
  •  攒了一身酷
    2020-11-28 13:46

    To select a specific range of characters you can do something like this in iOS 5+

    int start = 2;
    int end = 5;
    UITextPosition *startPosition = [self positionFromPosition:self.beginningOfDocument offset:start];
    UITextPosition *endPosition = [self positionFromPosition:self.beginningOfDocument offset:end];
    UITextRange *selection = [self textRangeFromPosition:startPosition toPosition:endPosition];
    self.selectedTextRange = selection;
    

    Since UITextFields and other UIKit elements have their own private subclasses of UITextPosition and UITextRange you can not create new values directly, but you can use the text field to create them for you from a reference to the beginning or end of the text and an integer offset.

    You can also do the reverse to get integer representations of the start and end points of the current selection:

    int start = [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.start];
    int end = [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.end];
    

    Here is a category which adds methods to handle selections using NSRanges. https://gist.github.com/4463233

提交回复
热议问题