iOS 7 UITextView 链接检测在 UITableView 中崩溃



我在UITableView中设置了一个自定义UITableView单元格,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"CELL_IDENTIFIER";
    SGCustomCell *cell = (SGCustomCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) cell = [[SGCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    cell = [self customizedCell:cell withPost:[postsArray objectAtIndex:indexPath.row]];
    return cell;
}

我像这样设置单元格(特别是将UITextView.text设置为 nil - 如此答案中所述):

descriptionLabel.text = nil;
descriptionLabel.text = post.postDescription;
descriptionLabel.frame = CGRectMake(leftMargin - 4, currentTitleLabel.frame.origin.y + currentTitleLabel.frame.size.height + 10, self.frame.size.width - topMargin * 3, 100);
[descriptionLabel sizeToFit];

这些单元格是 100% 可重复使用的,UITextView像这样启动的(如您所见,没什么特别的):

descriptionLabel = [[UITextView alloc] init];
descriptionLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:11];
descriptionLabel.editable = NO;
descriptionLabel.scrollEnabled = NO;
descriptionLabel.dataDetectorTypes = UIDataDetectorTypeLink;
descriptionLabel.frame = CGRectMake(leftMargin, currentTitleLabel.frame.origin.y + currentTitleLabel.frame.size.height + 10, self.frame.size.width - topMargin * 3, 10);
[self addSubview:descriptionLabel];

但是当表格有大约 50 个单元格并且当我快速滚动它时,我会出现以下崩溃:

Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds'

这绝对是荒谬的 - 我注释掉这一行 - descriptionLabel.dataDetectorTypes = UIDataDetectorTypeLink;并且应用程序停止崩溃!我花了几个小时试图找出问题所在,现在我只是得到了这个。

在 iOS 7.0.3 上测试

当两个数据类型的单元格在使用相同的单元格标识符。这似乎是iOS中的一个错误,但Apple可能有充分的理由以这种方式实现它。(记忆方面)

因此,唯一的100%防弹解决方案是为细胞提供唯一标识符包含数据类型。当然,这并不意味着您将为表格中的所有单元格设置唯一标识符,因为它会占用太多内存,并且您的表格滚动速度会非常慢。

您可以使用 NSDataDetector 来确定是否在文本中找到匹配的类型,然后才将找到的对象另存为单元格标识符,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *row = [self.dataSource objectAtIndex:indexPath.row];
    static NSDataDetector *detector = nil;
    if (!detector)
    {
        NSError *error = NULL;
        detector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink | NSTextCheckingTypePhoneNumber error:&error];
    }
    NSTextCheckingResult *firstDataType = [detector firstMatchInString:row
                                                               options:0
                                                                 range:NSMakeRange(0, [row length])];
    NSString *dataTypeIdentifier = @"0";
    if (firstDataType)
    {
        if (firstDataType.resultType == NSTextCheckingTypeLink)
            dataTypeIdentifier = [(NSURL *)[firstDataType URL] absoluteString];
        else if (firstDataType.resultType == NSTextCheckingTypePhoneNumber)
            dataTypeIdentifier = [firstDataType phoneNumber];
    }
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell_%@", dataTypeIdentifier];
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
...

注意:将 NSDataDetector 初始化为 *检测器为静态而不是为每个单元格初始化它可以提高性能。

我可以重现你的崩溃。在 TableViewCell 子类中实现以下方法

- (void)prepareForReuse
{
    [super prepareForReuse];
    [descriptionLabel setDataDetectorTypes: UIDataDetectorTypeNone];
}

并在设置文本之前- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath中添加以下调用:

[descriptionLabel setDataDetectorTypes: UIDataDetectorTypeLink];

为我工作。也许它取消了文本视图中正在进行的绘图,并以这种方式避免崩溃。

编辑:在设置文本之前调用[descriptionLabel setDataDetectorTypes: UIDataDetectorTypeNone];[descriptionLabel setDataDetectorTypes: UIDataDetectorTypeLink];似乎也可以修复崩溃

如果您使用的是 iOS6 或更高版本,则可以使用 NSDataDetector 制作可归属的字符串并将其用作 TextView 文本。我们将要使用的是以下方法的修改版本。 该方法采用一个字符串和一些已经预定义的属性(如字体和文本颜色),并将在第 100 个链接后停止。但是,它在多个电话号码方面存在一些问题。您需要为转义地址的 URL 定义自己的代码。 NSDataDetector位取自Apple的NSDataDetector参考:https://developer.apple.com/librarY/mac/documentation/Foundation/Reference/NSDataDetector_Class/Reference/Reference.html

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string attributes:attributes];
__block NSUInteger count = 0;
if (!_dataDetector)
{
    NSError *error = nil;
    _dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeAddress | NSTextCheckingTypePhoneNumber | NSTextCheckingTypeLink
                                                    error:&error];
}
[_dataDetector enumerateMatchesInString:string
                                options:0
                                  range:NSMakeRange(0, [string length])
                             usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
                                 NSRange matchRange = [match range];
                                 if ([match resultType] == NSTextCheckingTypeLink)
                                 {
                                     NSURL *url = [match URL];
                                     if (url)
                                     {
                                         [attributedString addAttribute:NSLinkAttributeName value:url range:matchRange];
                                     }
                                 }
                                 else if ([match resultType] == NSTextCheckingTypePhoneNumber)
                                 {
                                     NSString *phoneNumber = [NSString stringWithFormat:@"tel:%@",[match phoneNumber]];
                                     NSURL *url = [NSURL URLWithString:phoneNumber];
                                     if (url)
                                     {
                                         [attributedString addAttribute:NSLinkAttributeName value:url range:matchRange];
                                     }
                                 }
                                 else if ([match resultType] == NSTextCheckingTypeAddress)
                                 {
                 //Warning! You must URL escape this!
                                     NSString *address = [string substringWithRange:matchRange];
                 //Warning! You must URL escape this!
                                     NSString *urlString = [NSString stringWithFormat:@"http://maps.apple.com/?q=%@",address];
                                     NSURL *url = [NSURL URLWithString:urlString];
                                     if (url)
                                     {
                                         [attributedString addAttribute:NSLinkAttributeName value:url range:matchRange];
                                     }
                                 }
                                 if (++count >= 100) *stop = YES;
                             }];
return attributedString;

最新更新