Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Created May 4, 2012 09:18
Show Gist options
  • Save odrobnik/2593533 to your computer and use it in GitHub Desktop.
Save odrobnik/2593533 to your computer and use it in GitHub Desktop.
Control caret by dragging on Keyboard
- (void)keyboardWillShow:(NSNotification *)notification
{
NSArray *appWindows = [[UIApplication sharedApplication] windows];
UIWindow *keyboardWindow = [appWindows lastObject];
UIView *keyboardView = [keyboardWindow.subviews objectAtIndex:0];
keyboardView = [keyboardView.subviews objectAtIndex:0];
keyboardView = [keyboardView.subviews objectAtIndex:0];
keyboardView = [keyboardView.subviews objectAtIndex:0];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[keyboardView addGestureRecognizer:pan];
}
- (void)pan:(UIPanGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateBegan)
{
dragStartPosition = textView.selectedTextRange.start;
dragStartCaretRect = [textView caretRectForPosition:dragStartPosition];
dragStartPoint = CGPointMake(CGRectGetMidX(dragStartCaretRect), CGRectGetMidY(dragStartCaretRect));
}
else if (gesture.state == UIGestureRecognizerStateChanged)
{
//CGPoint location = [gesture locationInView:textView];
CGPoint offset = [gesture translationInView:textView];
CGPoint newLocation = dragStartPoint;
newLocation.x += offset.x;
newLocation.y += offset.y;
UITextPosition *position = [textView closestPositionToPoint:newLocation];
textView.selectedTextRange = [textView textRangeFromPosition:position toPosition:position];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment