我在 TableViewCell 中有一个标签,其中有多行文本。最初在标签上只显示一行。我在那个单元格上有一个按钮。我想通过单击按钮直到标签文本的最高位置来扩展单元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"tabCell";
   _cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...
   NSManagedObject *device = [self.persons objectAtIndex:indexPath.row];

   UILabel *nameLabel = (UILabel*)[_cell.contentView viewWithTag:2];
  nameLabel.text = [NSString stringWithFormat:@"%@", [device valueForKey:@"name"]];

   UILabel *dateLabel = (UILabel *)[_cell.contentView viewWithTag:3];
   dateLabel.text = [NSString stringWithFormat:@"%@",[device valueForKey:@"date"]];

   UILabel *descLabel = (UILabel *)[_cell.contentView viewWithTag:4];
//descTextView.text = [NSString stringWithFormat:@"%@",[device valueForKey:@"desc"]];


   UIImageView *personImage = (UIImageView *)[_cell.contentView viewWithTag:1];
   UIImage *personImg = [UIImage imageWithData:[device valueForKey:@"image"]];
   personImage.image = personImg;

    UIButton *viewMoreButton = (UIButton *)[_cell.contentView viewWithTag:5];
    [viewMoreButton addTarget:self
             action:@selector(myAction)
   forControlEvents:UIControlEventTouchUpInside];

    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:[device valueForKey:@"desc"]
                                                                 attributes:@{ NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:17]}];


    reqFrame=[attrString boundingRectWithSize:CGSizeMake(descLabel.frame.size.height, CGFLOAT_MAX)options:NSStringDrawingUsesLineFragmentOrigin
                                  context:nil];


    descLabel.attributedText = attrString;




    return _cell;
}

- (void)myAction{

   //what to write here?

}

最佳答案

首先,在cellForRowAtIndexPath中构建单元不是一个好习惯。请改用willDisplayCellSee here why

其次,要做您想做的事情,您必须在heightForRowAtIndexPath中设置所需的高度。完成此操作后,在您的按钮选择器调用中使用刷新特定单元格

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationAutomatic];

实现是类似的:
- (void)buttonSelector
{
    myLabel.text = @"YOUR TEXT";
    [myLabel sizeToFit];
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathOfYourCell, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ...
    return yourLabel.height;
}

关于ios - 展开和折叠tableView单元格直到标签的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31019915/

10-15 17:28