2

我有一个基本UITableView的,我在网上填写了一个网络服务,但是我找不到根据我的高度来设置我的单元格高度(动态单元格数)的方法textView

这是我填充单元格的方式:

UITextView *textView = (UITextView *)[cell viewWithTag:106];
textView.text = [[stories objectAtIndex:indexPath.row] objectForKey:@"texte"];

在我的cellForRow方法中:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

我试过这个但得到一个错误EXC_BAD_ACCESS

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PerleCell"];
    UITextView *textView = (UITextView *)[cell viewWithTag:106];
    textView.text = [[stories objectAtIndex:indexPath.row] objectForKey:@"texte"];
    CGFloat *heightCell =  (CGFloat*)textView.text.length;
    return *heightCell;
}
4

1 回答 1

1

在以下方法中,您可以根据 textView 更改单元格的高度。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // Here check length of your textView
    // and after getting length return that length;
    NSString *myString = [[stories objectAtIndex:indexPath.row] objectForKey:@"texte"];
    CGSize maximumSize = CGSizeMake(300, 9999);
    UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
    CGSize myStringSize = [myString sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:UILineBreakModeWordWrap];
    return size.height;
}

同样在 cellForRowAtIndexPath 方法中以相同的方式计算字符串的宽度,然后相应地给出 yourtextView 的宽度框架。之后在单元格的 contentView 上添加您的 textview。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
     // Create cell here by using any style and for this you can google some what that how to create cell in UITableView
     // Here check length of your textView
     // and after getting length return that length;
     NSString *myString = [[stories objectAtIndex:indexPath.row] objectForKey:@"texte"];
     CGSize maximumSize = CGSizeMake(300, 9999);
     UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
     CGSize myStringSize = [myString sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:UILineBreakModeWordWrap];
     UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(0,0,300,size.height)];
     textView.text = myString;
     [cell.contentView addSubView:textView];
     return cell;
}
于 2013-02-17T14:42:56.127 回答