【发布时间】:2015-11-23 18:07:06
【问题描述】:
我想用一个显示图像的自定义 TableViewCell 实现一个 TableView。
为了简单起见,我只是使用自动布局将 UIImageView 放在 tableviewcell 中(如下图所示)。
我想要的是在 UIImageView 中显示图像,但是这些图像尺寸可以是任何尺寸并且不一致(纵向、横向、正方形)...
因此,我希望显示具有固定宽度(设备宽度)和尊重图像比例的动态高度的图像。我想要这样的东西:
很遗憾,我没能达到这个结果。
这是我实现它的方式 - (我正在使用 Haneke 从 URL 加载图像 - 图像存储在 Amazon S3 中):
class TestCellVC: UITableViewCell {
@IBOutlet weak var selfieImageView: UIImageView!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
func loadItem(#selfie: Selfie) {
let selfieImageURL:NSURL = NSURL(string: selfie.show_selfie_pic())!
self.selfieImageView.hnk_setImageFromURL(selfieImageURL, placeholder: nil, format: HNKFormat<UIImage>(name: "original"), failure: {error -> Void in println(error)
}, success: { (image) -> Void in
// Screen Width
var screen_width = UIScreen.mainScreen().bounds.width
// Ratio Width / Height
var ratio = image.size.height / image.size.width
// Calculated Height for the picture
let newHeight = screen_width * ratio
// METHOD 1
self.heightConstraint.constant = newHeight
// METHOD 2
//self.selfieImageView.bounds = CGRectMake(0,0,screen_width,newHeight)
self.selfieImageView.image = image
}
)
}
override func viewDidLoad() {
super.viewDidLoad()
// Register the xib for the Custom TableViewCell
var nib = UINib(nibName: "TestCell", bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: "TestCell")
// Set the height of a cell dynamically
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 500.0
// Remove separator line from UITableView
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
loadData()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("TestCell") as TestCellVC
cell.loadItem(selfie: self.selfies_array[indexPath.row])
// Remove the inset for cell separator
cell.layoutMargins = UIEdgeInsetsZero
cell.separatorInset = UIEdgeInsetsZero
// Update Cell Constraints
cell.setNeedsUpdateConstraints()
cell.updateConstraintsIfNeeded()
cell.sizeToFit()
return cell
}
}
我对动态高度的计算是正确的(我已经打印出来了)。我已经尝试了两种方法(在代码中描述),但都没有奏效:
- 设置 UIImageView 的 Height Autolayout 约束
- 修改 UIImageView 的框架
在此处查看方法 1 和 2 的结果:
【问题讨论】:
-
它显示的是什么?设置图像的新高度约束是正确的,但是 AFAICT,没有什么可以告诉您的表格单元格根据图像的高度更改其高度。
-
嗨!我已经添加了两种方法结果的链接。我会在哪里告诉表格单元格改变它的高度?我想,如果我没记错的话,Haneke 的函数“self.selfieImageView.hnk_setImageFromURL”是异步的,所以在加载之前我并没有真正得到 Cell 的高度。
-
你能解决这个问题吗,我也是这种情况?
-
@fabdarice,您为此使用的任何解决方案?
-
您找到任何解决方案了吗? @fabdarice
标签: ios swift uitableview uiimageview autolayout