我试图让UIImageView根据它给出的图片动态地改变它的高度。 UIImageView在自定义单元格内部。
以下是限制因素:
到目前为止,我已使用Interface Builder向UIImageView添加了以下约束:
我在代码中使用高度约束(称为import UIKit
class ImageTableViewCell: UITableViewCell {
@IBOutlet weak var postImage: UIImageView!
@IBOutlet weak var postHeight: NSLayoutConstraint!
var post:UIImage! = nil {
didSet {
let x = post.size.width
let y = post.size.height
var newHeight = (y / x) * self.frame.width
newHeight = newHeight > self.frame.width ? self.frame.width : newHeight
postHeight.constant = newHeight
postImage.contentMode = .ScaleAspectFit
postImage.image = post
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
)来更改UIImageView的高度,如下所示:
TryImageView[89952:2477907] 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:0x7aef8560 V:[UIImageView:0x7aef96b0(291.355)]>",
"<NSLayoutConstraint:0x7aef9b30 UIImageView:0x7aef96b0.top == UITableViewCellContentView:0x7aef9340.topMargin - 8>",
"<NSLayoutConstraint:0x7aef9b90 UITableViewCellContentView:0x7aef9340.bottomMargin == UIImageView:0x7aef96b0.bottom - 8.5>",
"<NSLayoutConstraint:0x7ae5e990 'UIView-Encapsulated-Layout-Height' V:[UITableViewCellContentView:0x7aef9340(291)]>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7aef8560 V:[UIImageView:0x7aef96b0(291.355)]>
运行时,控制台显示它无法满足某些约束。并输出:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 90
self.tableView.rowHeight = UITableViewAutomaticDimension
}
表视图在viewDidLoad()中有这个,因为单元格也需要调整大小。
pe.ClipRectangle
关于为什么我的约束不起作用的任何想法? 感谢
答案 0 :(得分:0)
您正在为图像视图设置约束:
删除高度限制。假设单元格的高度为50.您无法修复图像视图的高度。如果它覆盖整个细胞,它的高度也将是50。您需要找出图像的高度,并将它们放在一个数组中。
var heights = [CGFloat]()
当你找到自己的高度时:
heights = [50, 60, 70]
然后在heightForRowAtIndexPath
方法中,返回这些高度。
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return heights[indexPath.row]
}
您还应该设置图片视图的contentMode
。
imageView.contentMode = .ScaleAspectFit