I have a UITextView with some texts. I need to select the text by swiping on textview. I mean when we swipe on the content of textview it should be selected and want to get that string to assign to a NSString object. is there any method to achieve this. Please suggest me some solutions to do that.
You can add pan gesture to UITextView to get CGPoint(finger positon), then use UITextInput protocol method to translate CGPoint to UITextPosition, then translate to UITextRange. Use UITextRange to select text programatically.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.textView.editable=NO;
UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(translatePan:)];
[self.textView addGestureRecognizer:pan];
UIMenuItem *menuItem = [[UIMenuItem alloc]initWithTitle:@"翻译" action:@selector(translate)];
[[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:menuItem]];
}
- (void)translatePan:(UIPanGestureRecognizer *)ges
{
CGPoint point = [ges locationInView:ges.view];
if (ges.state == UIGestureRecognizerStateBegan)
{
startPoint = point;
}
else if (ges.state == UIGestureRecognizerStateChanged || ges.state == UIGestureRecognizerStateEnded)
{
UITextPosition *start = [self.textView closestPositionToPoint:startPoint];
UITextPosition *end = [self.textView closestPositionToPoint:point];
UITextRange *range = [self.textView textRangeFromPosition:start toPosition:end];
[self.textView select:self.textView];
self.textView.selectedTextRange = range;
}
if (ges.state == UIGestureRecognizerStateEnded)
{
UIMenuController *mvc=[UIMenuController sharedMenuController];
[mvc setTargetRect:CGRectMake(startPoint.x, startPoint.y, point.x-startPoint.x, 20) inView:self.textView];
[mvc update];
[mvc setMenuVisible:YES animated:YES];
}
}
- (void)translate
{
NSLog(@"selected text:%@",[self.textView.text substringWithRange:self.textView.selectedRange]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With