【问题标题】:How to create CollectionView cells one after another in Swift? [closed]如何在 Swift 中一个接一个地创建 CollectionView 单元格? [关闭]
【发布时间】:2016-08-02 10:33:23
【问题描述】:

这个问题已经在 Objective-C 中得到解答,但我无法理解解决方案,因为我不了解 Objective-C。

我正在制作一个演示墙纸浏览器应用程序,并要求它在应用程序启动屏幕的集合视图中显示缩略图。 我设法完成了工作,但是这些图像是一起加载的,这需要很长时间才能加载(比如说)40 张图像。

如何设置我的视图控制器,以便将缩略图一张一张地加载到集合视图中,而不是一起加载?

以下是 Swift 文件。

ViewController.Swift

class ViewController: UIViewController , UICollectionViewDataSource {

@IBOutlet weak var collectionView: UICollectionView!


let imageFetcher = ImageFetcher()
var initialItem = 5

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return initialItem
}

       func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! CollectionViewCell
    cell.backgroundColor = UIColor.redColor()
   // cell.imageView.image = imageFetcher.ImageArray[indexPath.row]
    return cell
}


 }

【问题讨论】:

  • 你需要搜索一个收藏视图教程。
  • 显然没有关于“一个接一个地加载集合视图单元格”的主题。通常的 CollectionView 教程具有简单且常用的方式来创建单元格等。
  • CollectionViewCells 不是一次性创建的,它们是在显示之前创建和配置的,因此如果您只是显示一些具有图片。
  • 我想说问题不在于您的 CollectionView 代码,而在于您获取所显示图像的方式。
  • 先生,代码没有问题。它只是需要一些额外的功能来进行顺序单元加载。

标签: ios swift xcode uicollectionview


【解决方案1】:

我为你写了一些模板代码。希望这会有所帮助。

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var collectionView: UICollectionView!

    var colors = [UIColor]()

    var timer = NSTimer()

    var counter = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        self.colors.append(UIColor.randomColor())

        self.timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: #selector(addCellToCollectionView), userInfo: nil, repeats: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }


    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)

        self.timer.invalidate()

    }


    //MARK: - CollectionView Delegate -
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return self.colors.count
    }

    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        UIView.animateWithDuration(0.6, animations: {

            cell.alpha = 1

        })
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath)
        cell.alpha = 0
        cell.layer.cornerRadius = 12
        cell.backgroundColor = self.colors[indexPath.row]

        return cell
    }


    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let width = (collectionView.frame.size.width-20)/3
        let height = width
        let cellSize = CGSize(width: width, height: height)

        return cellSize
    }



    //MARK: - Timer Selector -
    func addCellToCollectionView(){

        self.counter += 1

        if counter < 30{

            self.colors.append(UIColor.randomColor())
            self.collectionView.reloadSections(NSIndexSet(index: 0))

        }else{

            self.timer.invalidate()
        }

    }

}



//MARK: - Extensions -

extension CGFloat{

    static func random() -> CGFloat {
        return CGFloat(arc4random()) / CGFloat(UInt32.max)
    }

}

extension UIColor{

    static func randomColor() -> UIColor {
        // If you wanted a random alpha, just create another
        // random number for that too.
        return UIColor(red:   .random(),
                       green: .random(),
                       blue:  .random(),
                       alpha: 1.0)
    }

}

不要忘记在您的 .storyboard 或 .xib 文件中设置 可重复使用的单元格标识符

UPDATE 3 Aug 15:27(对 GoldenBanana 的回答的建议)

var counter = 0

func addCells(timer : NSTimer){

    if(counter == imageFetcher.ImageArray.count){
        timer.invalidate()
        return
    }

    counter = counter + 1

    let indexPath = NSIndexPath(forItem: counter-1 , inSection: 0)
    collectionView.insertItemsAtIndexPaths([indexPath])
}



func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print("numberOfItemsInSection method just ran")                                                    //timeline indicator
    return counter

}

【讨论】:

  • 不能同意你的观点,抱歉。这个想法是您迭代地将元素添加到 collectionView 数据源并在每次迭代后重新加载 collectionVew。这样,单元格就会一一出现。
  • 感谢 Elena 的解决方案。我正在努力理解它并让它发挥作用。
  • 金香蕉,欢迎!我的解决方案可能缺乏解释,请询问您是否需要。
  • Yo Elena,我运行了一个稍微不那么复杂的代码版本并让它工作。然而,实施速度非常慢。如果你有时间,请看一下并提出一些建议。
  • 图片太大可能会导致性能下降。我用平均大小的图像测试了你的代码,看起来完全没问题。
【解决方案2】:

我终于能够使用 Elena 的代码中所示的计时器技术使单元的顺序加载工作。

如果这对任何人都有帮助,要回答这个问题,需要做以下事情

  1. 制作一个定时器
  2. 制作一个可变数组
  3. 计时器有一个动作 Method(addCells) 将对象从 dataSource 数组添加到可变数组
  4. 可变数组会随着时间的流逝(在计时器中指定)动态扩展自身,并用于填充 collectionView。

ViewController.swift

  class ViewController: UIViewController , UICollectionViewDataSource {


@IBOutlet weak var collectionView: UICollectionView!

let imageFetcher = ImageFetcher()

var mutableArray : NSMutableArray = []

override func viewDidLoad() {
    super.viewDidLoad()

    imageFetcher.setImageURL()
    NSTimer.scheduledTimerWithTimeInterval(01, target: self, selector: #selector(addCells), userInfo: nil, repeats: true)
    // Do any additional setup after loading the view, typically from a nib.
}

func addCells(timer : NSTimer){

    var counter = 0
    mutableArray.addObject(imageFetcher.ImageArray[counter])
    counter = counter + 1
    let indexPath = NSIndexPath(forItem: mutableArray.count-1 , inSection: 0)
    collectionView.insertItemsAtIndexPaths([indexPath])
    if(mutableArray.count == imageFetcher.ImageArray.count){
        timer.invalidate()
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    print("numberOfItemsInSection method just ran")                                                    //timeline indicator
    return mutableArray.count

}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! CollectionViewCell
       cell.imageView.image = imageFetcher.ImageArray[indexPath.row]
       return cell
}
}

ImageFetcher.swift

  class ImageFetcher {



var newImage : UIImage?
var ImageArray = [UIImage]()
var imageURL : NSURL?{
    didSet{  newImage = nil
             Adder()
        }
    }

func setImageURL(){
imageURL = DemoURLs.randomImageUrl
}


func fetchImage() {
    if let url = imageURL{
       let imageData = NSData(contentsOfURL: url)
        if imageData != nil{
            self.newImage  = UIImage( data: imageData! )
        } else {
            self.newImage = nil

        }
       }
    }

func Adder(){
    for _ in 1...20 {

        fetchImage()
        ImageArray.append(newImage!)

    }
}
}

此答案之前由 rdelmar 先生在这里用 Objective-C 语言回答过: Loading UICollectionViewCell one at a time。

【讨论】:

  • 1.你不应该在addCells 函数之外声明counter 吗?否则每次调用addCells counter 再次等于零。
  • 好的,我明白了。您的代码之所以有效,只是因为您不是真正的用户counter。如果你使用它,你根本不需要mutableArray。
  • 我对您的代码进行了一些更改(*请参阅我的答案的更新)以使其更清晰。
  • GoldenBanana,感谢您接受我的回答。您是否设法解决了性能缓慢的问题?
  • 我是 iOS 的新手,而不是大规模编程,所以这需要一段时间。但我认为它与多线程有关。我用 imageFetcher.swift 文件更新了我的答案,供您查看。
猜你喜欢
  • 1970-01-01
  • 2017-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
相关资源
最近更新 更多