【发布时间】:2020-08-29 03:58:06
【问题描述】:
我需要在UITableViewCell 中渲染图像。
API返回图像的原始高度和宽度,所以我相信我应该能够计算出比例。但是我不确定如何使用自动布局进行布局。
final class ContentArticleImage: UITableViewCell {
var ratio: CGFloat? { // 1000 / 600 (width / height)
didSet {
guard let ratio = ratio else { return }
contentImageView.heightAnchor.constraint(equalTo: widthAnchor, multiplier: 1 / ratio).isActive = true
}
}
private lazy var contentImageView = configure(UIImageView(frame: .zero), using: {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = .darkGray
$0.contentMode = .scaleAspectFit
})
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureUI()
}
required init?(coder: NSCoder) {
return nil
}
}
private extension ContentArticleImage {
func configureUI() {
addSubview(contentImageView)
NSLayoutConstraint.activate([
contentImageView.topAnchor.constraint(equalTo: topAnchor, constant: 12),
contentImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12),
contentImageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -12),
contentImageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12)
])
}
}
我尝试了类似上述的方法,但出现自动布局错误
(
"<NSLayoutConstraint:0x600002885b30 V:|-(12)-[UIImageView:0x7ffe3551e170] (active, names: '|':OneHubApp.ContentArticleImage:0x7ffe3551ddc0'ContentArticleImage' )>",
"<NSLayoutConstraint:0x600002885c70 UIImageView:0x7ffe3551e170.bottom == OneHubApp.ContentArticleImage:0x7ffe3551ddc0'ContentArticleImage'.bottom - 12 (active)>",
"<NSLayoutConstraint:0x600002885ea0 UIImageView:0x7ffe3551e170.height == 0.548298*OneHubApp.ContentArticleImage:0x7ffe3551ddc0'ContentArticleImage'.width (active)>",
"<NSLayoutConstraint:0x6000028860d0 'UIView-Encapsulated-Layout-Height' OneHubApp.ContentArticleImage:0x7ffe3551ddc0'ContentArticleImage'.height == 251 (active)>",
"<NSLayoutConstraint:0x600002886080 'UIView-Encapsulated-Layout-Width' OneHubApp.ContentArticleImage:0x7ffe3551ddc0'ContentArticleImage'.width == 414 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600002885c70 UIImageView:0x7ffe3551e170.bottom == OneHubApp.ContentArticleImage:0x7ffe3551ddc0'ContentArticleImage'.bottom - 12 (active)>
使用原始高度/宽度我应该如何计算单元格中图像的高度?
编辑 我的单元格是使用以下方法呈现的:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CONTENT_CELL", for: indexPath) as! ContentArticleImage
cell.ratio = asset.width / asset.height
cell.selectionStyle = .none
return cell
}
【问题讨论】:
-
您需要显示更多代码。您如何以及在何处设置比率?
-
抱歉,高度/宽度来自 api 响应,并且当单元格在
cellForRowAt中出列时,我将值设置为var ratio: CGFloat? { // 1000 / 600 (width / height) } -
我 99% 确定我知道您的问题是什么,但没有看到您的 cellForRowAt 方法,我无法发布解决方案。也许您可以使用代码更新您的帖子。另外,不清楚“原始高度/宽度”是什么意思
-
我现在添加它:)
-
我已将其添加到帖子底部
标签: ios swift uitableview uiimageview aspect-ratio