Sir*_*ens 2 objective-c cursor uitextview
我有一个UITextView,我想要两个按钮.当用户点击后退按钮时,我希望光标向后移动1个字符.当他们点击前进按钮时,光标应向前移动1个字符.我怎么能这样做?
我是为你写的,参考下面的答案.你可以将我写的代码放到一个基本项目中并试一试.
解决方案的想法:
您可以通过指定要选择的文本范围以编程方式选择文本块(请参阅参考).你问什么是范围?它基本上是一个起始位置和长度.由于您只关心光标位置,因此可以忽略长度(即将其保持为零)并将"选择"的起始位置调整为+1或-1.
参考:
代码说明:
在下面的代码中,有两个按钮(前进和后退)和每个按钮的目标方法,用于更改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];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1950 次 |
| 最近记录: |