我试图使用 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
是正确的我用了。所以问题是UITextRange
从 textview 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/