在UIImageView和UITableViewCell之间添加NSLayoutConstraint

时间:2017-06-12 16:21:00

标签: ios uitableview uiimageview storyboard nslayoutconstraint

我试图在UITableViewController中的两个元素之间添加约束,到目前为止,我还没有能够。 UIImage视图位于UITableViewController内部,但在UITableView Cell之外。

我既不能使用StoryBoard,也不能以编程方式添加约束,因为Xcode告诉我,我不能在将要重用的对象上添加约束。

我尝试添加约束的原因是因为UIImageView会根据下载的图像大小动态调整大小。当出于某种原因无法下载图像时,它会使用默认图像,整个布局都会崩溃。

这是我的tableView的样子:

enter image description here

2 个答案:

答案 0 :(得分:1)

The problem is that constraints set a relation between two objects. As your tableViewCell will be reused you can't set the constraints to object that outside the cell.

Actually, you can get the size of the image on the cell and set the constraint to outside ImageView programatically according to cellImageView size.

For example, if the downloaded image width is imageCellWidth, and your outsize imageView should be 2 times bigger.

NSLayoutConstraint *imageViewWidth = [NSLayoutConstraint
                                     constraintWithItem:imageView
                                     attribute:NSLayoutAttributeWidth
                                     relatedBy:NSLayoutRelationEqual
                                     toItem:nil
                                     attribute:NSLayoutAttributeNonAnAttribure
                                     multiplier:1.0f
                             constant:imageCellWidth*2];
[imageView addConstraint: imageViewWidth];

If you need to change this constraint dynamically, just change the constant value

imageViewWidth.constant = newWidth;

答案 1 :(得分:1)

您可以考虑将UIImageView打包到UITableViewCell并将其作为UITableView中的第一个单元格。此外,您可以将表格视图中单元格的层次结构细分为2个部分,这样可以简化对单元格的跟踪。所以第一部分只包含UIImageView单元格,第二部分包含主单元格。

每当您从网络请求获得表明已提取图像的响应时,您可以调用tableView.reloadSections(IndexSet(integer: 0), with: .none)并在委托方法中返回正确的高度

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) {
  if indexPath.section == 0 {
    return imageHeight
  }
}