【发布时间】:2013-09-13 07:45:37
【问题描述】:
我正在使用下面的代码来检测在 UITextView 中点击的单词。这很好用,但我想检测一些特殊字符,比如?。 ? 在使用 UITextGranularityWord 时不会显示为单词的一部分,而且在使用 UITextGranularityCharacter 时我似乎也无法显示它。
如何检测对单个特殊字符(例如 ?)的点击?
-(NSString*)getWordAtPosition:(CGPoint)pos inTextView:(UITextView*)_tv
{
//eliminate scroll offset
pos.y += _tv.contentOffset.y;
//get location in text from textposition at point
UITextPosition *tapPos = [_tv closestPositionToPoint:pos];
//fetch the word at this position (or nil, if not available)
UITextRange * wr = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
if ([_tv textInRange:wr].length == 0) {//i.e. it's not a word
NSLog(@"is 0 length, check for characters (e.g. ?)");
UITextRange *ch = [_tv.tokenizer rangeEnclosingPosition:tapPos withGranularity:UITextGranularityCharacter inDirection:UITextLayoutDirectionRight];
NSLog(@"ch range: %@ ch text: %@",ch, [_tv textInRange:ch] ); // logs: ch range: (null) ch text:
if ([[_tv textInRange:ch] isEqualToString:@"?"]) {
return [_tv textInRange:ch];
}
}
return [_tv textInRange:wr];
}
【问题讨论】:
-
我不确定它是如何工作的——如果我的返回被点击字符的函数不能返回
?,我该如何使用NSCharacterSet?我不想检查字符串中是否存在?,但前提是它存在于用户点击的位置。 -
好吧,我误会了对不起。你想得到在你的 textView 中被点击的字符,对吧?我测试了你的代码,它适用于“?”,你可以用同样的方法测试所有的特殊字符吗?
-
这真的很奇怪——因为我无法检测到单词中的特殊字符:
foo?变为foo或者它们本身就是?。它只返回一个空的 NSRange 和字符串。我正在使用GM,也许这是一个错误? -
同样的问题 iOS 7.1.2 :(
标签: ios uitextview nsrange