将光标移动到位置Objective-C

时间:2012-06-30 17:36:08

标签: objective-c cursor uitextview

我有UITextView,我想要两个按钮。当用户点击后退按钮时,我希望光标向后移动1个字符。当他们点击前进按钮时,光标应向前移动1个字符。我怎么能这样做?

2 个答案:

答案 0 :(得分:5)

我是为你写的,参考下面链接的答案。你可以将我写的代码放到一个基本项目中并试一试。

解决方案的想法:

您可以通过指定要选择的文本范围以编程方式选择文本块(请参阅参考资料)。你问什么是范围?它基本上是一个起始位置和长度。由于您只关心光标位置,您可以忽略长度(即将其保持为零)并将“选择”的起始位置调整为+1或-1。

<强>参考:

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

代码说明:

在下面的代码中,有两个按钮(前进和后退)和每个按钮的目标方法,用于更改UITextView中的光标位置。请注意,tv是UITextView的类变量/属性(需要声明为此类)。

守则:

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *forward = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    forward.frame = CGRectMake(20, 20, 100, 50);
    [forward setTitle:@"Forward" forState:UIControlStateNormal];
    [forward addTarget:self action:@selector(moveForward:) forControlEvents:UIControlEventTouchUpInside];

    UIButton *back = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    back.frame = CGRectMake(130, 20, 100, 50);
    [back setTitle:@"Back" forState:UIControlStateNormal];    
    [back addTarget:self action:@selector(moveBack:) forControlEvents:UIControlEventTouchUpInside];

    tv = [[UITextView alloc] initWithFrame:CGRectMake(20, 120, 280, 100)];
    [self.view addSubview:forward];
    [self.view addSubview:back];
    [self.view addSubview:tv];    
}


-(void)moveForward:(id)sender {
    UITextRange *selectedRange = [tv selectedTextRange];
    // Calculate the new position, - for left and + for right

    if (tv.selectedRange.location < tv.text.length) {
        UITextPosition *newPosition = [tv positionFromPosition:selectedRange.start offset:1];

        UITextRange *newRange = [tv textRangeFromPosition:newPosition toPosition:newPosition];

        // Set new range
        [tv setSelectedTextRange:newRange];
    }
}

-(void)moveBack:(id)sender {
    UITextRange *selectedRange = [tv selectedTextRange];
    // Calculate the new position, - for left and + for right

    if (tv.selectedRange.location > 0) {
        UITextPosition *newPosition = [tv positionFromPosition:selectedRange.start offset:-1];

        UITextRange *newRange = [tv textRangeFromPosition:newPosition toPosition:newPosition];

        // Set new range
        [tv setSelectedTextRange:newRange];
    }
}

答案 1 :(得分:1)

theSelectedRange确定[theTextView selectedRange];范围 通过减去或添加偏移量来更新location theSelectedRange属性 如果没有选择(插入点),则length属性为零 使用theTextView.selectedRange = theSelectedRange;定位光标 确保新范围不超出theTextView内容的范围。