草庐IT

ios - 加载更多数据时 CollectionView 重复单元格

coder 2023-07-16 原文

问题:

我有一个 CollectionView,它将 UIimage 加载到每个单元格中。但是我的问题是,当我加载带有更多图像的其他单元格时,它们似乎是重复的。我不太明白是什么导致了我的代码中出现这种情况。 可能是因为可重复使用的电池有问题吗?

谁能看出为什么会这样?

注意:包含图像的数组没有重复项

问题视频: https://www.youtube.com/watch?v=vjRsFc8DDmI

问题图片:

这是我的 collectionView 函数:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //#warning Incomplete method implementation -- Return the number of items in the section
    if self.movies == nil
    {
      return 0

    }

    return self.movies!.count

}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
{
    let cell =    
      collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, 
        forIndexPath: indexPath) as! UpcomingCollectionViewCell

   if self.movies != nil && self.movies!.count >= indexPath.row
    {
        // Calc size of cell
        cell.frame.size.width = screenWidth / 3
        cell.frame.size.height = screenWidth / 3 * 1.54

        let movies = self.movies![indexPath.row]
        if(movies.posterPath != "" || movies.posterPath != "null"){
        cell.data = movies.posterPath
        }
        else{
        cell.data = nil
        }
        // See if we need to load more movies
        let rowsToLoadFromBottom = 5;
        let rowsLoaded = self.movies!.count
        if (!self.isLoadingMovies && (indexPath.row >= (rowsLoaded - rowsToLoadFromBottom)))
        {
            let totalRows = self.movieWrapper!.totalResults!
            let remainingMoviesToLoad = totalRows - rowsLoaded;
            if (remainingMoviesToLoad > 0)
            {
                self.loadMoreMovies()
            }
        }
}
   else
{
        cell.data = nil
}

    return cell
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
    return CGSize(width: screenWidth/3, height: screenWidth/3*1.54)
}

这里我从 Wrapper 类加载数据:

func loadFirstMovies()
{

    isLoadingMovies = true

    Movies.getMovies({ (movieWrapper, error) in
        if error != nil
        {
            // TODO: improved error handling
            self.isLoadingMovies = false
            let alert = UIAlertController(title: "Error", message: "Could not load first movies \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
        self.addMoviesFromWrapper(movieWrapper)
        self.activityIndicator.hidden = true
        self.isLoadingMovies = false
        self.collectionView.reloadData()
    })
}

func loadMoreMovies(){

    self.isLoadingMovies = true
    if self.movies != nil && self.movieWrapper != nil && self.movieWrapper!.page < self.movieWrapper!.totalPages
    {
        // there are more species out there!
        Movies.getMoreMovies(self.movieWrapper, completionHandler: { (moreWrapper, error) in
            if error != nil
            {
                // TODO: improved error handling
                self.isLoadingMovies = false
                let alert = UIAlertController(title: "Error", message: "Could not load more movies \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert)
                alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
                self.presentViewController(alert, animated: true, completion: nil)
            }
            print("got more!")
            self.addMoviesFromWrapper(moreWrapper)
            self.isLoadingMovies = false
            self.collectionView.reloadData()
        })
    }
}

func addMoviesFromWrapper(wrapper: MovieWrapper?)
{
    self.movieWrapper = wrapper
    if self.movies == nil
    {
        self.movies = self.movieWrapper?.results
    }
    else if self.movieWrapper != nil && self.movieWrapper!.results != nil
    {
        self.movies = self.movies! + self.movieWrapper!.results!
    }
}

最后我在 viewDidLoad()

中调用:loadFirstMovies()

编辑: 即将到来的 CollectionViewCell

class UpcomingCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var imageView: UIImageView!


var data:String?{
    didSet{
        self.setupData()
    }
}

func setupData(){

   self.imageView.image = nil // reset the image

    if let urlString = data{
        let url =  NSURL(string: "http://image.tmdb.org/t/p/w342/" + urlString)
        self.imageView.hnk_setImageFromURL(url!)


      }
    }  
 }

最佳答案

这是典型的 TableView / Collection View 设置问题。

任何时候您使用像 dequeueReusableCellWithReuseIdentifier: 这样的出列方法回收单元格时,您必须始终完全配置单元格中的所有 View ,包括将所有文本字段/ ImageView 设置为它们的起始值。您的代码有几个 if 语句,如果 if 的条件为假,则您不会在单元格中设置 View 。您需要使用 else 子句从单元格的 View 中清除旧内容,以防上次使用单元格时留下内容。

编辑:

更改您的 cellForItemAtIndexPath 方法,使其像这样开始:

func collectionView(collectionView: UICollectionView, 
  cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
{
    let cell =    
      collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, 
        forIndexPath: indexPath) as! UpcomingCollectionViewCell
    cell.imageView.image = nil;  //Remove the image from the recycled cell
//The rest of your method ...

关于ios - 加载更多数据时 CollectionView 重复单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33674788/

有关ios - 加载更多数据时 CollectionView 重复单元格的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  3. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  4. 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返回它复制的字节数,但是当我还没有下

  5. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

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

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

  7. 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

  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. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  10. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

随机推荐