本文介绍了使用UITextPosition,从textInRange获取前一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找高低,无法弄清楚如何做到这一点。假设我有一个这样的字符串:

I've been searching high and low and can't figure out how to do this. Lets say I have a string like this:

NSString *string = @"&foo !foo";

我要做的是区分文本中的两个foos(听起来很有趣哈哈)视图。当我点击一个时,我想知道它前面有哪个(&或!)。以下是我的说法:

What I'm trying to do is differentiate between the two foos (sounds funny haha) inside a text view. When I click on one, I want to know which (& or !) comes before it. Here's how I'm getting the word:

UITapGestureRecognizer *recognizer = (UITapGestureRecognizer *)sender;
UITextView *TV = (UITextView*)recognizer.view;
CGPoint location = [recognizer locationInView:TV];
location.y += TV.contentOffset.y;
UITextPosition *tapPosition = [TV closestPositionToPoint:CGPointMake(location.x, location.y)];
UITextRange *textRange = [TV.tokenizer rangeEnclosingPosition:tapPosition
    withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
NSString *tappedWord = [TV textInRange:textRange];

我无法弄清楚如何获得前一个角色。 TV.tokenizer UITextGranularityCharacter 只获取最接近的字母,而不是符号。对此的任何解决方案?

I can't figure out how to get the previous character. TV.tokenizer UITextGranularityCharacter only gets the closest letter, not the symbol. Any solutions for this?

推荐答案

检查:,将 UITextRange 转换为 NSRange (我将打电话给 selectedRange )。

Check: Convert selectedTextRange UITextRange to NSRange to convert your UITextRange to a NSRange (that I'll call selectedRange).

用我之前对链接问题的回答激励我,您需要在代码末尾添加此内容:

Inspiring me with the previous answer to the linked question, you'd need to add this at the end of your code:

UITextPosition *beginning = TV.beginningOfDocument;
UITextPosition *selectionStart = textRange.start;
UITextPosition *selectionEnd = textRange.end;
NSInteger location = [TV offsetFromPosition:beginning toPosition:selectionStart];
NSInteger length = [TV offsetFromPosition:selectionStart toPosition:selectionEnd];
NSRange selectedRange = NSMakeRange(location,lenght);
NSRange range = NSMakeRange(selectedRange.location-1,1) //Maybe need to check if selectedRange.location>0
NSString *yourCharString = [[TV text] substringWithRange:range];

这篇关于使用UITextPosition,从textInRange获取前一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:47