ios - 再次动态调整 UITableViewCell 的大小

标签 ios xcode uitableview

好吧,我已经搜索了很多来解决我的问题,但是,我还没有找到任何有用的东西。

我有我的自定义单元格,它可以(或不能)包含图像、文本、标题等,因此我需要根据其内容设置行的高度。 像这两个:http://db.tt/AVBKYuEY http://db.tt/HbnXMMFn

我制作它们的唯一方法是通过 Storyboard。

所以,我调用 tableView:cellForRowAtIndex: 并将全部内容放在那里 然后我想设置行的高度,但我做不到,因为行的高度是在 tableView:height...: 中设置的,它在 tableView 之前调用:cellForRowAtIndex:

顺便说一句,我的 Storyboard 中也有限制,所以,如果我可以使用它们来计算单元格高度,那就太好了。

而且当我旋转 iPhone 时它​​也完美地改变了宽度,事实上我不能改变高度很奇怪

如何解决我的问题?

最佳答案

可以在tableView:heightForRowAtIndexPath:中设置高度。您可以在该方法中访问索引路径,因此可以访问向单元格提供数据的数组的索引。因此,您需要查看该数据,进行确定单元格高度所需的任何计算,然后返回该值。

编辑后:这是计算多行标签高度的示例。我创建了一个临时标签,用该行将包含的文本填充它,然后使用 sizeWithFont:constrainedToSize:LineBreakMode: 进行计算:

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 0; // allows label to have as many lines as needed
    label.text = _objects[indexPath.row][@"detail2"]; // this is the data I'm passing in the detail label
    CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(300, 300000) lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat h = labelSize.height;
    return h + 50; //50 is base height for my cell with only one line of text, determined empirically
}

关于ios - 再次动态调整 UITableViewCell 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13820127/

相关文章:

ios - 调整 UITableViewCell 的 NSLayoutConstraint 错误

ios - 如果用于 'numberOfRowsIndexPath' .count 的数组为 0,则更改 TableView 的大小

iOS Storyboard : Views outside of the ViewController and on Top of the Scene (between First Responder and Exit boxes)

ios - 在物理设备上测试时图像的白条和黑条

ios - 'NSInvalidArgumentException',原因 : '*** -[NSURL initFileURLWithPath:]: nil string parameter'

ios - 删除和替换文件 Xcode 6 后 Storyboard 空白

xcode - 在将 iOS 应用程序上传到 AppStore 之前尝试验证该应用程序时出错

ios - 如何使用 WKWebView 点击电话号码

ios - 在多个类中添加 touchesBegan

ios - Swift 对类进行子类化的问题