jjzjj

ios - 滚动后 UITableView 单元格正确

coder 2024-01-28 原文

我创建了一个帖子的 Swift UITableView,每个帖子都包含一些文本和一张图表图像。使用 SDWebImage 和 Firebase 异步加载图像。图片具有不同的高度,但宽度固定。

这是显示显示问题的简短视频:https://youtu.be/QzQFT2z0GjA

有些单元格第一次显示不正确,但滚动后看起来很完美。我阅读了有关使用 layoutIfNeeded 和 setNeedsLayout as suggested in this post 的信息或 iOS 11 UITableViewAutomaticDimension,但它似乎不适用于我的情况。

这是我的代码:

var postArray : [Post] = [Post]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    postTableView.delegate = self
    postTableView.dataSource = self
    aLaUneWidthConstraint.constant = view.frame.size.width/2

    etatFranceWidthConstraint.constant = view.frame.size.width/2
    postTableView.register(UINib(nibName:"TableViewCell", bundle: nil), forCellReuseIdentifier: "postCell")



    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
    activityIndicator.startAnimating()

    retrievePosts()

}

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return postArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! TableViewCell

    tableView.separatorStyle = UITableViewCellSeparatorStyle.none
    cell.selectionStyle = UITableViewCellSelectionStyle.none

    cell.postTitle.text = postArray[indexPath.row].title
    cell.postSource.text = postArray[indexPath.row].source
    cell.postChart.sd_setImage(with: URL(string: postArray[indexPath.row].chartURL!), placeholderImage: UIImage(named: "placeholder.png")) { (image, error, cache, url) in
        cell.chartHeightConstraint.constant = ((cell.postChart.image?.size.height)!/2)
        cell.setNeedsLayout()
        cell.layoutIfNeeded()
    }

    return cell

}

func retrievePosts() {

    let postDB = Database.database().reference().child("Posts")

    postDB.observe(.childAdded, with: { (snapshot) in

        let snapshotValue = snapshot.value as! NSDictionary

        let title = snapshotValue["title"] as! String
        let source = snapshotValue["source"] as! String
        let chartURL = snapshotValue["chartURL"] as! String
        let category = snapshotValue["category"] as! String

        let post = Post(data: snapshotValue)
        post.title = title
        post.source = source
        post.chartURL = chartURL
        post.category = category

        self.postArray.append(post)

        self.activityIndicator.stopAnimating()
        self.activityView.isHidden = true
        self.activityView.frame.size.height = 0
        self.postTableView.reloadData()

    })

}

有什么想法吗?提前致谢。

最佳答案

解决方案包括在 Post 对象中添加 chartWidth 和 chartHeight 参数,并为 Firebase 数据库中的每个帖子添加它们的值,然后设置一些约束以在下载图像之前预先计算单元格高度。

在 TableViewCell.swift 添加:

func setChartSize(size: CGSize) {
    postChart.removeConstraint(postChartRatioConstraint)

    postChartRatioConstraint = NSLayoutConstraint(
        item: postChart,
        attribute: .height,
        relatedBy: .equal,
        toItem: postChart,
        attribute: .width,
        multiplier: (size.height / size.width),
        constant: 0)

    postChart.addConstraint(postChartRatioConstraint)
}

在 ViewController 中使用 setChartSize 函数:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! TableViewCell

    tableView.separatorStyle = UITableViewCellSeparatorStyle.none
    cell.selectionStyle = UITableViewCellSelectionStyle.none

    let post = postArray[indexPath.row]

    cell.postTitle.text = post.title
    cell.postSource.text = post.source

    cell.postChart.sd_setShowActivityIndicatorView(true)
    cell.postChart.sd_setIndicatorStyle(.white)

    cell.setChartSize(size: CGSize(width: post.chartWidth!, height: post.chartHeight!))
    cell.postChart.sd_setImage(
        with: URL(string: post.chartURL!),
        placeholderImage: UIImage(named: "placeholder.png"),
        options: [.continueInBackground],
        completed: nil)

    return cell
}

下载图表后调整单元格大小等任何其他选项都会生成滚动跳转。

关于ios - 滚动后 UITableView 单元格正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48057813/

有关ios - 滚动后 UITableView 单元格正确的更多相关文章

  1. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. ruby-on-rails - 正确的 Rails 2.1 做事方式 - 2

    question的一些答案关于redirect_to让我想到了其他一些问题。基本上,我正在使用Rails2.1编写博客应用程序。我一直在尝试自己完成大部分工作(因为我对Rails有所了解),但在需要时会引用Internet上的教程和引用资料。我设法让一个简单的博客正常运行,然后我尝试添加评论。靠我自己,我设法让它进入了可以从script/console添加评论的阶段,但我无法让表单正常工作。我遵循的其中一个教程建议在帖子Controller中创建一个“评论”操作,以添加评论。我的问题是:这是“标准”方式吗?我的另一个问题的答案之一似乎暗示应该有一个CommentsController参

  4. ruby - 我可以将我的 README.textile 以正确的格式放入我的 RDoc 中吗? - 2

    我喜欢使用Textile或Markdown为我的项目编写自述文件,但是当我生成RDoc时,自述文件被解释为RDoc并且看起来非常糟糕。有没有办法让RDoc通过RedCloth或BlueCloth而不是它自己的格式化程序运行文件?它可以配置为自动检测文件后缀的格式吗?(例如README.textile通过RedCloth运行,但README.mdown通过BlueCloth运行) 最佳答案 使用YARD直接代替RDoc将允许您包含Textile或Markdown文件,只要它们的文件后缀是合理的。我经常使用类似于以下Rake任务的东西:

  5. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  6. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  7. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

  8. ruby-on-rails - Prawn - 表格单元格内的链接 - 2

    我正在尝试用Prawn生成PDF。在我的PDF模板中,我有带单元格的表格。在其中一个单元格中,我有一个电子邮件地址:cell_email=pdf.make_cell(:content=>booking.user_email,:border_width=>0)我想让电子邮件链接到“mailto”链接。我知道我可以这样链接:pdf.formatted_text([{:text=>booking.user_email,:link=>"mailto:#{booking.user_email}"}])但是将这两行组合起来(将格式化文本作为内容)不起作用:cell_email=pdf.make_c

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. ruby - 如何在 RVM 下将 Bundler 安装到 @global gemset,这是正确的方法吗 - 2

    我在OSX上(如果重要的话)。如果我使用RVM安装Ruby,它会默认将Bundler安装到@globalgemset假设我想要一个不同版本的bundler。我假设我需要做的就是执行geminstallbundler--version但是,这会将bundler安装到默认gemset并且RVM不会为其设置路径。因此,如果我键入bundler,它仍会启动一个与Ruby一起安装到@global中的bundler两个问题:如何将bundler安装到@globalgemset。将bundler安装到@globalgemset中的模式是否正确,或者我遗漏了什么 最佳答案

随机推荐