突出显示并滚动到UICollectionView中的随机单元格

时间:2016-01-25 14:23:03

标签: ios swift uicollectionview

我想要一个按钮,按下时,会在UICollectionView中选择一个随机项,然后滚动到它。

到目前为止,我有这段代码:

@IBAction func randomClicked(sender: UIButton) {
    self.randomItem = Int(arc4random_uniform(UInt32(self.members.count)))
    dispatch_async(dispatch_get_main_queue(), {
        self.collectionView.reloadData()
        self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: self.randomItem, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
    })
}

这会突出显示我想要的单元格(因为我在cellForIndexAtItem)中设置了样式,但视图根本不滚动。我确定我遗漏了一些明显的东西,但我不能看看它是什么!

我尝试过一个更简单的版本,只是为了测试滚动位:

@IBAction func randomClicked(sender: UIButton) {
        self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: 30, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
}

但同样,没有滚动。

更新:2月27日 我已经重新创建了整个视图,但问题仍然存在 - 没有滚动!这是完整的代码:

import Foundation
import UIKit
class GroupViewController : UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    @IBOutlet weak var collectionView: UICollectionView!
    var random = -1
    // pick a single random student to scroll to
    @IBAction func randomClicked(sender: UIButton) {
        self.random = Int(arc4random_uniform(UInt32(200)))
        self.collectionView.reloadData() // reloads the visible cells, highlighting the random one
        self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: self.random, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: true)
    }
    // 200 example cells
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 200
    }
    // draw the cells
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as! MyCollectionViewCell
        cell.title.text = "Title"
        cell.subtitle.text = "\(indexPath.row)"
        cell.title.textColor = UIColor.whiteColor()
        cell.subtitle.textColor = UIColor.whiteColor()
        if(random == indexPath.row) {
            cell.backgroundColor = UIColor.purpleColor()
        } else {
            cell.backgroundColor = UIColor.lightGrayColor()
        }
        return cell
    }
    // 4 columns per row
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        let size = collectionView.frame.width
        return CGSize(width: (size/4)-(24/4), height: (size/4)-(24/4))
    }
}

1 个答案:

答案 0 :(得分:0)

对于您想要使用的集合视图。

NSIndexPath(forItem: 30, inSection: 0)

not,表格视图。

NSIndexPath(forRow: 30, inSection: 0)