【发布时间】:2016-05-31 20:13:00
【问题描述】:
我正在尝试让 UIImageView 根据给出的图片动态更改其高度。 UIImageView 位于自定义单元格内。
以下是限制条件:
- 必须从屏幕边缘跨越到另一边缘。
- 它的高度必须是动态的,并且不能超过框架的宽度。
到目前为止,我已经使用 Interface Builder 向 UIImageView 添加了以下约束:
我使用代码中的高度约束(简称postHeight)来改变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
}
}
运行时,控制台显示它无法满足某些约束。和输出:
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)]>
表格视图在其 viewDidLoad() 中有这个,因为单元格也需要调整大小。
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 90
self.tableView.rowHeight = UITableViewAutomaticDimension
}
关于为什么我的约束不起作用的任何想法? 谢谢
【问题讨论】:
标签: ios swift uitableview uiimageview autolayout