【问题标题】:iOS: Collection view, selectItemAtIndexPath programmatically doesn't workiOS:集合视图,selectItemAtIndexPath 以编程方式不起作用
【发布时间】:2014-01-01 01:27:10
【问题描述】:

我不知道为什么这不起作用。 indexOfIcon 是正确的,部分是正确的(用 NSLog 检查)如果我选择一个,一切都是正确的。但是这条线没有做任何事情......为什么?如果选择它应该有一个蓝色边框。这在“手动”而不是使用代码时效果很好..

- (void)viewWillAppear:(BOOL)animated
{
    NSUInteger indexOfIcon;
    if(self.mainCategory.icon){
        indexOfIcon = [self.icons indexOfObject: self.mainCategory.icon];
    } else {
        indexOfIcon = 0;
    }
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:indexOfIcon inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionBottom];
}

【问题讨论】:

  • 确保允许选择属性设置为 YES 并正确设置委托,并确保在选择项目后您没有重新加载集合视图

标签: ios uicollectionview


【解决方案1】:

添加

    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.selected = YES;

然后单元格将被选中。

命令[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:indexOfIcon inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionBottom]; 告诉collectionView,单元格处于选中状态,但不要设置单元格的状态。

【讨论】:

  • 我现在把它改成了这个,但也不起作用: NSIndexPath *iconIndexPath = [NSIndexPath indexPathForRow:indexOfIcon inSection:0]; [self.collectionView selectItemAtIndexPath:iconIndexPath 动画:YES scrollPosition:UICollectionViewScrollPositionBottom]; UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:iconIndexPath]; cell.selected = YES;
  • 确保collectionview 已完成加载单元格。要对此进行测试,请在您的 viewWillAppear 中创建一个 [self performSelector:@selector(test) withObject:nil afterDelay:2];并在测试方法中选择单元格的代码。
  • 你太棒了!显然它还没有加载单元格。但是我怎样才能在没有这种延迟的情况下解决这个问题呢?现在您在集合视图中,2 秒后单元格被选中。有没有比 viewWillAppear 更好的放置代码的位置?
  • 将延迟更改为 0。它不像我希望的那样干净,但它是我知道的唯一可行的解​​决方案。 stackoverflow.com/questions/14020027/…
  • 我已将其放入 viewDidAppear 中,延迟为 0 并且运行顺畅 :-)
【解决方案2】:

多年后的选择似乎工作正常(即使在 viewDidLoad 中:)

NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
[_collection selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionLeft];

成功触发单元格的-setSelected:

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2015-08-31
    • 2018-04-02
    • 2017-10-22
    • 2020-01-24
    • 2013-10-09
    相关资源
    最近更新 更多