我希望以编程方式显示适合屏幕宽度的表格视图中的远程图像列表。
我的表格视图有这样的约束:tableView.rowHeight = UITableViewAutomaticDimension
。
我创建一个单元格,添加图像并创建约束。
let cell = UITableViewCell()
let url = URL(string: "https://static.pexels.com/photos/411089/pexels-photo-411089.jpeg")
let data = NSData(contentsOf: url!)
let imageView = UIImageView()
cell.addSubview(imageView)
imageView.image = UIImage(data: data as Data!)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.leadingAnchor.constraint(equalTo: cell.leadingAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: cell.trailingAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: cell.topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: cell.bottomAnchor).isActive = true
return cell
我得到了这个(部分照片):
图像渲染不正确,高度太大。我试图修复它并添加了一个比率约束:
let ratio = imageView.image!.size.height/imageView.image!.size.width
imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: ratio).isActive = true
之后,图像显示正确,但我得到关于约束的非致命错误:
每张图片出错:
2017-09-10 23:50:52.490946+0300 MyHelloWorld[35126:1135489] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x60800009eaa0 UIImageView:0x7fe4605236e0.height == 0.667391*UIImageView:0x7fe4605236e0.width (active)>",
"<NSLayoutConstraint:0x60800009ec30 H:|-(0)-[UIImageView:0x7fe4605236e0] (active, names: '|':UITableViewCell:0x7fe4608a0c00 )>",
"<NSLayoutConstraint:0x60800009ecd0 UIImageView:0x7fe4605236e0.trailing == UITableViewCell:0x7fe4608a0c00.trailing (active)>",
"<NSLayoutConstraint:0x60800009ed20 V:|-(0)-[UIImageView:0x7fe4605236e0] (active, names: '|':UITableViewCell:0x7fe4608a0c00 )>",
"<NSLayoutConstraint:0x60800009edc0 UIImageView:0x7fe4605236e0.bottom == UITableViewCell:0x7fe4608a0c00.bottom (active)>",
"<NSLayoutConstraint:0x60800009efa0 'UIView-Encapsulated-Layout-Height' UITableViewCell:0x7fe4608a0c00.height == 213.5 (active)>",
"<NSLayoutConstraint:0x60800009eeb0 'UIView-Encapsulated-Layout-Width' UITableViewCell:0x7fe4608a0c00.width == 320 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60800009eaa0 UIImageView:0x7fe4605236e0.height == 0.667391*UIImageView:0x7fe4605236e0.width (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
我不知道这个约束 - 异常究竟意味着什么。而且我不知道如何解决它。请帮助,我已经花了几天时间来解决这个问题。
如何解决此错误?
感谢。
答案 0 :(得分:1)
您应该将约束的优先级从1000设置为999.这样,可以首先应用表格视图单元格的封装布局尺寸。
let imageRatioConstraint = imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: ratio)
imageRatioConstraint.priority = 999
imageRatioConstraint.isActive = true