【问题标题】:Best way to achieve dynamic cell height for an UIImageView inside a tableViewCell?为 uitableViewCell 中的图像视图实现动态单元格高度的最佳方法?
【发布时间】:2016-06-15 04:06:31
【问题描述】:

试图获得平滑的动态高度,目前它可以工作,但它从一种尺寸到动态尺寸出现故障,看起来不太好。

这是我在cellForRowAtIndexPath中的代码

 cell.productImageView.file = (PFFile *)object[@"image"];
 [cell.productImageView loadInBackground:^(UIImage * _Nullable image, NSError * _Nullable error) {


            cell.imageHeightConstraint.constant = image.size.height / image.size.width * cell.cardView.frame.size.width;
            [cell.productImageView setNeedsUpdateConstraints];

            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
            if (indexPath != nil) {
                [self.tableView beginUpdates];
                [self.tableView endUpdates];
            }

            [UIView animateWithDuration:0.50f animations:^{
                [cell.cardView layoutIfNeeded];
            }];

     }];

如您所见,我只是在更新 ImageView 的高度约束,然后相应地调整单元格的大小。但还是有问题。

有没有更好的办法?

【问题讨论】:

  • 你不应该在cellForRowAtIndexPath 中搞乱布局。您应该实现一个 heightForRowAtIndexPath 方法来设置行高。
  • 你能告诉我一个编程解决方案吗? @user3386109
  • 创建自定义单元格 xib 并使用自动布局约束。
  • 使用xib有什么好处?
  • @user3386109 我没有改变代码中单元格的高度,我改变的是imageView的高度

标签: ios objective-c uitableview uiimageview


【解决方案1】:

您可以通过在viewDidLoadautolayout 中添加以下行来解决您的问题。

_tblView.delegate = self;
_tblView.dataSource = self;
self._tblView.estimatedRowHeight = 80; // The estimatedRowHeight but if is more this autoincremented with autolayout
self._tblView.rowHeight = UITableViewAutomaticDimension;
[self._tblView setNeedsLayout];
[self._tblView layoutIfNeeded];
self._tblView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) ;

这里有更多信息:

https://www.raywenderlich.com/87975

http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/

希望对你有帮助..!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多