我试图UITextView characterRangeAtPoint在我的代码中使用文本视图UITextRanges中的一些CGPoints内容。然后我使用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我使用的,这是正确的。所以问题是UITextRange从textview characterRangeAtPoint. 似乎在 IOS 7 中characterRangeAtPoint没有返回给定的正确文本范围CGPoint。所以textview offsetFromPosition: toPosition:无法返回正确的偏移量。
但我在 IOS 6 中使用了相同的代码,并且效果很好。我还检查了 的参考资料characterRangeAtPoint,但没有发现有用的信息。
有谁知道characterRangeAtPointIOS 7发生了什么?为了让它像在 IOS 6 中一样正常工作,我应该怎么做?