如何将光标位置向前移动特定长度?

时间:2012-10-10 11:16:59

标签: objective-c ios cocoa-touch

我有UITextField,如何根据某些条件动态更改光标位置到特定长度?

2 个答案:

答案 0 :(得分:1)

使用textview.selectedRange

NSRange selection = [textview.text rangeOfString:@"SomeText" options:NSCaseInsensitiveSearch];
if( selection.location != NSNotFound ){
    textview.selectedRange =  selection;
    textview.selectedRange = NSMakeRange(selection.location, 0);
}

它可能会帮助你

答案 1 :(得分:0)

使用此链接可能会帮助您解决问题。希望它有用!! :)

Change cursor in UITextField when set new text

并在UITextField中找到光标位置

// Get the selected text range
    UITextRange *selectedRange = [self selectedTextRange];

    // Calculate the existing position, relative to the end of the field (will be a - number)
    int pos = [self offsetFromPosition:self.endOfDocument toPosition:selectedRange.start];

    // Change the text
    self.text = lastValidated; 

    // Work out the position based by offsetting the end of the field to the same
    // offset we had before editing
    UITextPosition *newPos = [self positionFromPosition:self.endOfDocument offset:pos];

    // Reselect the range, to move the cursor to that position
    self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];

快乐的编码......