在 UIImageView 和 UITableViewCell 之间添加 NSLayoutConstraint
Add NSLayoutConstraint between UIImageView and UITableViewCell
我正在尝试在 UITableViewController 中的两个元素之间添加约束,但到目前为止,我还无法做到。 UIImage 视图在 UITableViewController 内部,但在 UITableView Cell 外部。
我既不能使用 StoryBoard,也不能以编程方式添加约束,因为 Xcode 告诉我不能在将要重用的对象上添加约束。
我尝试添加约束的原因是因为 UIImageView 会根据下载的图像大小动态调整大小。当由于某种原因无法下载图像时,它使用默认图像并且整个布局分崩离析。
这是我的 tableView 的样子:
问题是约束设置了两个对象之间的关系。由于您的 tableViewCell 将被重复使用,因此您不能将约束设置为在单元格外的对象。
实际上,您可以获取单元格上图像的大小,并根据 cellImageView 大小以编程方式将约束设置到 ImageView 外部。
例如,如果下载的图像宽度为imageCellWidth,那么您的超大imageView应该大2倍。
NSLayoutConstraint *imageViewWidth = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNonAnAttribure
multiplier:1.0f
constant:imageCellWidth*2];
[imageView addConstraint: imageViewWidth];
如果需要动态更改此约束,只需更改常量值即可
imageViewWidth.constant = newWidth;
您可以考虑将您的 UIImageView
包装到 UITableViewCell
中并将其作为 UITableView
中的第一个单元格。此外,您可以将 table 视图中的单元格层次结构分解为 2 个部分,这样可以简化对单元格的跟踪。因此,第一部分将仅包含 UIImageView
单元格,第二部分将包含您的主要单元格。
每当您从网络请求中获得指示已获取图像的响应时,您可以调用 tableView.reloadSections(IndexSet(integer: 0), with: .none)
并在委托方法中 return 正确的高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
return imageHeight
}
}
我正在尝试在 UITableViewController 中的两个元素之间添加约束,但到目前为止,我还无法做到。 UIImage 视图在 UITableViewController 内部,但在 UITableView Cell 外部。
我既不能使用 StoryBoard,也不能以编程方式添加约束,因为 Xcode 告诉我不能在将要重用的对象上添加约束。
我尝试添加约束的原因是因为 UIImageView 会根据下载的图像大小动态调整大小。当由于某种原因无法下载图像时,它使用默认图像并且整个布局分崩离析。
这是我的 tableView 的样子:
问题是约束设置了两个对象之间的关系。由于您的 tableViewCell 将被重复使用,因此您不能将约束设置为在单元格外的对象。
实际上,您可以获取单元格上图像的大小,并根据 cellImageView 大小以编程方式将约束设置到 ImageView 外部。
例如,如果下载的图像宽度为imageCellWidth,那么您的超大imageView应该大2倍。
NSLayoutConstraint *imageViewWidth = [NSLayoutConstraint
constraintWithItem:imageView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNonAnAttribure
multiplier:1.0f
constant:imageCellWidth*2];
[imageView addConstraint: imageViewWidth];
如果需要动态更改此约束,只需更改常量值即可
imageViewWidth.constant = newWidth;
您可以考虑将您的 UIImageView
包装到 UITableViewCell
中并将其作为 UITableView
中的第一个单元格。此外,您可以将 table 视图中的单元格层次结构分解为 2 个部分,这样可以简化对单元格的跟踪。因此,第一部分将仅包含 UIImageView
单元格,第二部分将包含您的主要单元格。
每当您从网络请求中获得指示已获取图像的响应时,您可以调用 tableView.reloadSections(IndexSet(integer: 0), with: .none)
并在委托方法中 return 正确的高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
return imageHeight
}
}