Swift 中的动态表格图像视图
Posted
技术标签:
【中文标题】Swift 中的动态表格图像视图【英文标题】:Dynamic Table Image View in Swift 【发布时间】:2018-05-11 04:48:50 【问题描述】:我有一个与此处发布的非常相似的问题 (Dynamic UIImageView Size Within UITableView),我正在尝试从 Firebase 动态检索图像,并使生成的 tableview 调整到图像的高度,给定屏幕上的固定宽度纵横比。我读过的所有文章都说基于 cellforRowAt 进行单元格计算,但我的实际图像在 TableViewCell 内。有人可以帮忙吗?
表格视图控制器:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedTableViewCell", for: indexPath) as! FeedTableViewCell
cell.configureCell(post: postArray[indexPath.row])
return cell
TableViewCell:
func configureCell(post: Post)
self.postImage.sd_setImage(with: URL(string: post.postImageURL),
placeholderImage: UIImage(named: "default"))
【问题讨论】:
使用 Disptach.main.asyncell. postImage.kf.setImage(with: URL) _, _, _, _ in cell.layoutIfNeeded() 【参考方案1】:你在设置图像方法的完成处理程序中有cell.setNeedsLayout()
,像这样:
cell. postImage.kf.setImage(with: URL) _, _, _, _ in
cell.layoutIfNeeded()
【讨论】:
对不起,我不明白。那个代码去哪儿了?我的图片在 tableviewcell 中 你必须在完成处理程序self.postImage.sd_setImage
中下载单元格后进行布局@【参考方案2】:
首先,您需要使用 Autolayout 来计算正确的单元格高度,方法是创建一组适当的约束,根据内容确定单元格的高度。我假设你这样做了。
然后你必须告诉tableView
你想让它使用Autolayout来计算高度:
// my best estimation of the height
tableView.estimatedRowHeight = 144
// but the real height is calculated by autolayout
tableView.rowHeight = UITableViewAutomaticDimension
现在,如果自动布局可以正确计算 cellForRowAt
中的高度,这将起作用。但是由于图像是异步下载的,图像是稍后设置的,当单元格可能已经呈现时。这要求您提供一种方式,单元格可以告诉tableView
它已下载其内容并且需要重新计算其布局。为此,请在viewController
和tableView
中使用此方法:
func recalculateTableViewLayout()
self.tableView.beginUpdates()
self.tableView.setNeedsLayout()
self.tableView.endUpdates()
您需要将viewController
和tableView
的引用传递给每个单元格(我建议为此使用委托模式,为了简洁起见,我将直接使用它来简单地绘制它):
class FeedTableViewCell: UITableViewCell
weak var feedViewController: FeedViewController?
// etc.
而在cellForRowAt
:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedTableViewCell", for: indexPath) as! FeedTableViewCell
cell.feedViewController = self
cell.configureCell(post: postArray[indexPath.row])
return cell
然后使用sd_setImage
的完成处理程序告诉tableView
在图像下载时重新计算其布局:
func configureCell(post: Post)
self.postImage.sd_setImage(with: URL(string: post.postImageURL), placeholderImage: UIImage(named: "default")) (image, error, cache, url) in
self.feedViewController?.recalculateTableViewLayout()
【讨论】:
我的 self.postImage.sd_setImage(with: URL(string: post.postImageURL) 当前位于我的 tableviewcell 文件中,而不是 tableviewcontroller 是否重要?以上是关于Swift 中的动态表格图像视图的主要内容,如果未能解决你的问题,请参考以下文章
从 Swift (3.1) 表格视图中动态创建的单元格获取有序的文本字段数据