参考:
在UITextInput协议中,有selectedTextRange来表示光标的起始和结束位置,如果start和end相同则表示光标选中内容为空,只有光标。可以通过更改selectedTextRange来实现光标位置的移动
+(void) moveCursor:(id<UITextInput>)textInput inDirection:(UITextLayoutDirection)direction offset:(NSInteger)offset
{
UITextRange *range = textInput.selectedTextRange;
UITextPosition* start = [textInput positionFromPosition:range.start inDirection:direction offset:offset];
if (start)
{
[textInput setSelectedTextRange:[textInput textRangeFromPosition:start toPosition:start]];
}
}
左移光标,偏移1
[self moveCursor:textInput inDirection:UITextLayoutDirectionLeft offset:1];
右移光标,偏移1
[self moveCursor:textInput inDirection:UITextLayoutDirectionRight offset:1];
上移光标
[self moveCursor:textInput inDirection:UITextLayoutDirectionUp offset:1];
下移光标
[self moveCursor:textInput inDirection:UITextLayoutDirectionDown offset:1];
通过上述可以简单的实现光标的 上下左右所有移动,网上看了一圈应该是最简单的,特别是对上移和下移光标。兼容性上,在备忘录和safari里测试正常,说明对webview和textview都良好支持。
其他方法实现光标 上移,下移
主要思想就是得到当前光标的Rect,然后将光标的originY坐标增加光标对应的高度来表示 下移,将光标的originY坐标减小光标对应的高度来表示 上移。
如下代码表示下移光标。
UITextRange *range = textInput.selectedTextRange;
CGRect rect = [textInput caretRectForPosition:range.start];
CGFloat orignY = rect.origin.y+rect.size.height;
UITextPosition *start = [textInput closestPositionToPoint:CGPointMake(rect.origin.x, orignY)];
[textInput setSelectedTextRange:[textInput textRangeFromPosition:start toPosition:start]];