由于未捕获exception'CALayerInvalidGeometry',原因:'CALayer界限包含NaN:'

我正在开发一个图书应用程序,用户可以在TextView上更改字体大小。

当用户更改字体大小时,应用程序保存当前文本位置不会在用户更改字体大小后更改。

它在大多数情况下工作正常,但有时,当用户更改字体大小,应用程序得到这种错误,我仍然不能告诉如何解决这个问题。

由于未捕获exception'CALayerInvalidGeometry',原因:'CALayer界限包含NaN:[0 nan; 280 524]” *第一掷调用堆栈:(0x3231e3e7 0x3a019963 0x3231e307 0x33edb4d7 0x33edb30d 0x3419141f 0x3419b82f 0x342d1cf1 0x3414f80d 0xe7bf1 0xe607d 0xfad35 0x34218087 0x34218111 0x34218087 0x3421803b 0x34218015 0x342178cb 0x34217db9 0x341405f9 0x3412d8e1 0x3412d1ef 0x35e455f7 0x35e45227 0x322f33e7 0x322f338b 0x322f220f 0x3226523d 0x322650c9 0x35e4433b 0x341812b9 0xdf9f1 0xdf978)的libc ++ ABI。 dylib:terminate调用抛出exception

由于偶尔出现这个问题,我也无法100%重现这个问题。

这是代码。 有没有人有一个想法来解决这个问题? 提前致谢。

- (UITextRange *)getCurrentTextRange:(UITextView *)textView { CGRect bounds = textView.bounds; UITextPosition *start = [textView characterRangeAtPoint:bounds.origin].start; UITextPosition *end = [textView positionFromPosition:start offset:1]; UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end]; return textRange; } - (void)changeFontSize:(UIButton*)button { UITextRange *textRange = [self getCurrentTextRange:_textView]; int fontSize = [[NSUserDefaults standardUserDefaults] integerForKey:@"fontSize"]; //button.tag == 1 => decreaseFontSize if (button.tag == 1) { //set a minimum size if (fontSize <= [LSUniversalManager getFontSizeForMinimum]) { return; } fontSize--; //button.tag == 2 => increaseFontSize } else if (button.tag == 2) { fontSize++; } _textView.font = [UIFont systemFontOfSize:fontSize]; [[NSUserDefaults standardUserDefaults] setInteger:fontSize forKey:@"fontSize"]; //avoid shifting the scroll position after changing font size CGRect rect = [_textView firstRectForRange:textRange]; [_textView setContentOffset:CGPointMake(0, rect.origin.y)]; } 

在这里的某处,你会得到一个无效的输出,导致rect的值为NaN (一个特殊的浮点值,意思是“不是一个有效的浮点数”,最常见的是由零除)。 是否有可能你已经通过了一个无效的或无意义的UITextRange-firstRectForRange ? 如果UITextPosition *start引用文本中的最后一个字符,然后再创build另一个文本位置,而这个文本位置是结尾的一个字符,会发生什么?