【发布时间】:2013-09-25 10:25:52
【问题描述】:
我试图在我的代码中使用UITextView characterRangeAtPoint 在文本视图中的某个CGPoints 处获取UITextRanges。然后我使用来自UITextRanges 的UITextPositions 作为参数,并使用UITextView offsetFromPosition: toPosition: 来获取偏移量。它在 iOS 6 中运行良好。但是当我在 iOS 7 中尝试它时,无论我在 textview 中尝试什么CGPoint,它总是返回给我offset 0。
代码如下:
// 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,这是正确的。所以问题是从textview characterRangeAtPoint 返回的UITextRange。在 IOS 7 中,characterRangeAtPoint 似乎没有在给定的CGPoint 处返回正确的文本范围。所以textview offsetFromPosition: toPosition: 无法返回正确的偏移量。
但我在 IOS 6 中使用了相同的代码,并且效果很好。我也查了characterRangeAtPoint的引用,没有找到有用的信息。
有谁知道characterRangeAtPoint 在 IOS 7 中发生了什么?为了让它像在 IOS 6 中一样正常工作,我应该怎么做?
【问题讨论】:
标签: iphone ios ios6 uitextview ios7