iphone - 在 IOS 7 中,UITextView offsetFromPosition : toPosition: always return 0 with arguments of UITextPositions returned from UITextView characterRangeAtPoint

标签 iphone ios ios6 uitextview ios7

我试图使用 UITextView characterRangeAtPoint在我的代码中获取 UITextRanges在某些 CGPoints在 TextView 中。然后我使用了UITextPositions来自那些 UITextRanges作为参数并使用UITextView offsetFromPosition: toPosition:获得偏移量。它在 iOS 6 中运行良好。但是当我在 iOS 7 中尝试时,它总是返回 offset 0无论如何CGPoint我在 TextView 中尝试过。

这是代码:

// init the textview
textview = [[UITextView alloc] initWithFrame:CGRectMake(10, 50, 300, 500)];
textview.backgroundColor = [UIColor whiteColor];
[self.view addSubview:textview];

// load the txt file for testing  
NSError *error;
NSString *content = [[NSString alloc] initWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"] encoding:NSUTF8StringEncoding error:&error];
if (error) {
    NSLog(@"load string error:%@", [error localizedFailureReason]);
    return;
}

// set the text and font
textview.text = content;
UIFont *font = [UIFont systemFontOfSize:18];
textview.font = font;

// get text range at point (100, 100) and string offset from the beginning to this point 
UITextRange *textrange = [textview characterRangeAtPoint: CGPointMake(100, 100)];
NSInteger offset = [textview offsetFromPosition:textview.beginningOfDocument toPosition:textrange.start];
NSLog(@"offset = %d", offset);
offset返回的总是 0 .为了测试是不是因为UITextView offsetFromPosition: toPosition: ,我尝试了以下代码:
NSInteger offset1 = [textview offsetFromPosition:textview.beginningOfDocument toPosition:textview.endOfDocument];
NSLog(@"offset1 = %d", offset1);

它给了我offset1 = 5264 ,根据 test.txt 是正确的我用了。所以问题是UITextRangetextview characterRangeAtPoint 返回.似乎在 IOS 7 中 characterRangeAtPoint没有返回给定 CGPoint 的正确文本范围.所以textview offsetFromPosition: toPosition:无法返回正确的偏移量。

但我在 IOS 6 中使用了相同的代码,并且效果很好。我还检查了 characterRangeAtPoint 的引用资料,但没有找到有用的信息。

有谁知道 characterRangeAtPoint 发生了什么?在IOS 7?为了让它像在 IOS 6 中一样正常工作,我应该怎么做?

最佳答案

我遇到了同样的问题。而且我发现 characterRangeAtPoint 不会返回值,除非在 IOS 7 的 TextView 中至少更改或选择了一次文本。
我无法使此功能正常工作,因此我不得不避免使用它(我也尝试设置 setContentInset 但没有运气)。这是我的解决方法。我相信你可以做出类似的东西来适应你的情况。

// get the beginning position of the current line.
NSRange pos = [textView.text rangeOfString:@"\n" options:NSBackwardsSearch range:NSMakeRange(0,textView.selectedRange.location)];
if (pos.location == NSNotFound) pos.location = 0; // if the text has only one line.
NSLog(@"pos = %d",pos.location);

关于iphone - 在 IOS 7 中,UITextView offsetFromPosition : toPosition: always return 0 with arguments of UITextPositions returned from UITextView characterRangeAtPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19002387/

相关文章:

iphone - 使用 Core Motion 从加速度计数据获取位移

ios - 如何最好地处理核心数据 + iOS 状态恢复?

ios - Facebook iOS SDK 3.1.1 安装问题

iphone - 如何在iPhone上打开应用解锁

iphone - 如何更改图像中的特定颜色?

ios - 在 swift 中使用 uiimagepickercontroller 裁剪图像

iphone - NSLog - 奇怪的行为

ios - 隐藏字段留有空白

iphone - 使用缩放后 MKMapView 应用程序崩溃

ios - PhoneGap 2.4 中未显示飞溅微调器