回到我試圖用UITextView characterRangeAtPoint
在我的代碼在TextView的內一些CGPoints
得到UITextRanges
。然後我使用中的UITextPositions
作爲參數,並使用UITextView offsetFromPosition: toPosition:
來獲得偏移量。它在iOS 6中運行良好。但是當我在iOS 7中嘗試它時,無論CGPoint
我在textview中嘗試過,它總是會返回我offset 0
。在IOS 7,UITextView的offsetFromPosition:toPosition:總是UITextPositions的參數返回0,從UITextView的characterRangeAtPoint
下面是代碼:
// 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
的參考資料,但沒有找到有用的信息。
有沒有人知道IOS7中characterRangeAtPoint
發生了什麼?爲了使其功能與IOS 6中的一樣,我該怎麼做?
相關/可能重複 - [檢測點擊字符。 UITextView characterRangeAtPoint總是返回nil](http://stackoverflow.com/q/18925755)。 – Dukeling
可能的重複[Detecting tapped character。 UITextView characterRangeAtPoint總是返回nil](http://stackoverflow.com/questions/18925755/detecting-tapped-character-uitextview-characterrangeatpoint-always-returns-nil) –