如何在UITableView静态单元格中动态更改单元格高度

Kam*_*war 7 objective-c uitableview ios

我使用UITableViewControllerdetailView来显示一个实体细节.我在我的viewDidLoad方法中填充了PFQuery的一行数据.我有一个单元格,我正在使用标签,我想根据大小更改NSString大小.我检查了很多答案,但都与indexPath动态相关,我有静态单元格.My label显示完整的字符串,但我的单元格已修复.如何更改单元格的高度?请帮我纠正这个问题.

这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    PFQuery *query = [PFQuery queryWithClassName:@"Entities"];
    [query whereKey:@"name" equalTo:entityName];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            PFFile *thumbnail = [objects[0]  objectForKey:@"image"];
            detailsImageView.image = [UIImage imageNamed:@"loader.gif"];
            detailsImageView.file = thumbnail;
            [detailsImageView loadInBackground];
            detailLabel.numberOfLines = 0; // this label need dynamic height and its cell
            detailLabel.text = [objects[0]  objectForKey:@"descriptionLarge"];
            [detailLabel sizeToFit];
        } else {
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            NSLog(@"Error: %@", errorString);
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)

我试图通过选择单个单元格来执行以下操作,但它给了我UITableView错误,因为我没有定义tableView,如何定义或者如果您有任何其他好的解决方案请告诉我.

static NSString *simpleTableIdentifier = @"DetailsDesecriptionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
Run Code Online (Sandbox Code Playgroud)

我也对批评编码质量持开放态度,因此您的反馈对我来说很有价值.

L.L*_*.L. 16

如果是IOS 8 OR 9,则有一个简单的解决方法.

  1. 设置UILabel的约束.(上,左,下,右)
  2. 将UILabel的行设置为0
  3. 在ViewController的viewDidLoad方法中添加以下代码:
tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
Run Code Online (Sandbox Code Playgroud)
  1. 覆盖功能:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)


Jay*_*jar 3

如果您使用自动布局。将顶部、左侧和右侧约束添加到标签中。

然后heightForRowAtIndexPath创建你的单元格

static NSString *simpleTableIdentifier = @"DetailsDesecriptionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
Run Code Online (Sandbox Code Playgroud)

为标签设置值并在设置值后计算标签的尺寸

    [cell layoutIfNeeded];
    return cell.label.frame.origin.y+cell.label.frame.size.height;
Run Code Online (Sandbox Code Playgroud)

这将为您提供标签的准确高度,并且您的单元格高度将相同

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = @"DetailsDesecriptionCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
            cell.titleLabel.text=@"YOUR TEXT";
            [cell layoutIfNeeded];
            return cell.titleLabel.frame.origin.y+cell.titleLabel.frame.size.height;
}
Run Code Online (Sandbox Code Playgroud)