ios 如何以编程方式在collectionview中选择项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21639394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:23:16  来源:igfitidea点击:

How to select item in collectionview programmatically?

iosiphoneuicollectionviewuicollectionviewcell

提问by mrd

I have a UICollectionView. The UICollectionView's datasourceis a NSArrayof students (from CoreData). I want the current student item be selected/highlighted.

我有一个UICollectionView. 该UICollectionViewdatasourceNSArray学生(从CoreData)。我希望当前的学生项目是selected/ highlighted

How can I do this? I know there is a method:

我怎样才能做到这一点?我知道有一种方法:

- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
                     animated:(BOOL)animated 
               scrollPosition:(UICollectionViewScrollPosition)scrollPosition;

which takes as arguments an NSIndexPathand UICollectionViewScrollPosition.

它将一个NSIndexPath和作为参数UICollectionViewScrollPosition

I have the datasource (NSArrayof students populated from CoreData) and the student object to be selected.

我有数据源(NSArray来自填充CoreData的学生)和学生对象selected

So, how do I get the NSIndexPathand UICollectionViewScrollPosition? Or is there any other way to highlight an item?

那么,我如何获得NSIndexPathUICollectionViewScrollPosition?或者有没有其他方法可以突出显示项目?

回答by Shahin

You can simply use this after [self.collectionView reloadData]

你可以简单地使用它之后 [self.collectionView reloadData]

[self.collectionView 
   selectItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] 
                animated:YES
          scrollPosition:UICollectionViewScrollPositionCenteredVertically];

where indexis the index number for the selected student.

其中index是所选学生的索引号。

回答by Krunal

Swift

迅速

let indexPath = self.collectionView.indexPathsForSelectedItems?.last ?? IndexPath(item: 0, section: 0)
self.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: UICollectionView.ScrollPosition.centeredHorizontally)

回答by sgib

From your question I'm assuming you only ever have one selected student, I did a similar thing with a collection of icons the user could select. Firstly in view did load I did:

根据您的问题,我假设您只有一个选定的学生,我对用户可以选择的一组图标做了类似的事情。首先在视图中确实加载了我所做的:

override func viewDidLoad() {
    super.viewDidLoad()

    iconCollectionView.delegate = self
    iconCollectionView.dataSource = self
    iconCollectionView.allowsMultipleSelection = false
    iconCollectionView.selectItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), animated: false, scrollPosition: .None)
}

Here I default to selecting the first cell, you would use StudentArray.indexOfto get your selected student index. Then to show the which item is selected I did:

这里我默认选择第一个单元格,您将使用它StudentArray.indexOf来获取您选择的学生索引。然后显示我选择了哪个项目:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = iconCollectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! IconCollectionViewCell
    cell.imageView.image = UIImage(named: imageResourceNames.pngImageNames[indexPath.row])
    if cell.selected {
        cell.backgroundColor = UIColor.grayColor()
    }
    return cell
}

This is called when the collection is first displayed, then to react to changes in selection:

这在第一次显示集合时调用,然后对选择的更改做出反应:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    collectionView.cellForItemAtIndexPath(indexPath)?.backgroundColor = UIColor.grayColor()
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    collectionView.cellForItemAtIndexPath(indexPath)?.backgroundColor = UIColor.clearColor()
}

Obviously there are many ways to show cell selection, my way is simple but that's all I needed to do.

显然有很多方法可以显示单元格选择,我的方法很简单,但这就是我需要做的。

EDIT: Since posting the above I have realised it's simpler to just add an observer to selectedin the cell class:

编辑:自从发布上述内容后,我意识到selected在单元格类中添加一个观察者更简单:

class IconCollectionViewCell: UICollectionViewCell {

...

    override var selected: Bool {
        didSet {
            backgroundColor = selected ? UIColor.grayColor() : UIColor.clearColor()
        }
    }
}

With this in place the there is no need to handle didSelector didDeselector check for selected in cellForItemAtIndexPath, the cell does it automatically.

有了这个地方有没有需要处理didSelectdidDeselect或为您在选择cellForItemAtIndexPath,细胞自动执行它。

回答by x-rw

the signature has changes.

签名有变化。

didSelectItemAtIndexPath  to didSelectItemAt 

you check this please:

你检查一下:

_ collectionView

try with this please:

请试试这个:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){

        print(" selected",)
    }

回答by IsPha

Super late I know, but just for Record, for item x in section y:

我知道太晚了,但只是为了记录,对于第 y 部分中的项目 x:

 NSIndexPath *indexPath = [NSIndexPath indexPathForItem:x inSection:y];

if you want to just highlight an item programmatically, you need to call selectItemAtIndexPath method on the collection view itself like:

如果您只想以编程方式突出显示一个项目,则需要在集合视图本身上调用 selectItemAtIndexPath 方法,例如:

[theCollectionView selectItemAtIndexPath:indexPath
    animated:YES scrollPosition:UICollectionViewScrollPositionCenteredVertically];

if you want to simulate selecting an item programmatically and you get the code in did select gets called, you need to call selectItemAtIndexPath method on the view controller itself and pass to it your collection view as param like:

如果您想以编程方式模拟选择一个项目,并且您在 do select 中调用了代码,您需要在视图控制器本身上调用 selectItemAtIndexPath 方法并将您的集合视图作为参数传递给它,例如:

[theViewController collectionView:theCollectionView didSelectItemAtIndexPath:indexPath];

Now as sure thing, in order to get an item selected and the did select code gets called, you need to call both :D

现在可以肯定的是,为了选择一个项目并调用 did select 代码,您需要同时调用两者:D

[theCollectionView selectItemAtIndexPath:indexPath
    animated:YES scrollPosition:UICollectionViewScrollPositionCenteredVertically];

[theViewController collectionView:theCollectionView didSelectItemAtIndexPath:indexPath];

SWIFT version:

SWIFT 版本:

let indexPath = IndexPath(item: x, section: y)
theCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredVertically)
theViewController.collectionView(theCollectionView, didSelectItemAt: indexPath)

enjoy!

请享用!

回答by Vishal Chaudhari

let indexPathForFirstRow = IndexPath(row: 0, section: 0)
    paymentHeaderCollectionView.selectItem(at: indexPathForFirstRow, animated: false, scrollPosition: UICollectionViewScrollPosition.left)
    self.collectionView(paymentHeaderCollectionView, didSelectItemAt: indexPathForFirstRow)