TableView单元格中TextView的可变高度

时间:2013-02-17 14:29:26

标签: iphone ios objective-c uitableview

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

以下是我填充单元格的方式:

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

1 个答案:

答案 0 :(得分: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;
}