如何将单元格的值/字符串内容转换为nsindexpath



我有一个UICollectionView,其中填充了来自CoreData的内容。当视图加载时,我想预选/突出显示一些单元格。

我已经能够使用下面的代码获得预选的项目。高亮没有像我想的那样无缝地工作,但我可以让它工作。

- (void)preSelect {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:6 inSection:5];
    [self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    if ([[self.collectionView cellForItemAtIndexPath:indexPath] isSelected]) {
        [self.collectionView cellForItemAtIndexPath:indexPath].backgroundColor = [UIColor darkGrayColor];
        NSLog(@"selected count %i",[self.collectionView indexPathsForSelectedItems].count);
    }
}

我不想让预选硬编码。我想这样做:

NSIndexPath = indexPath where [value of cell] isEqual:@"NSString";

或者更好的

PFQuery *query = [PFQuery queryWithClassName:@"myClass"];
[query findObjectsInBackgroundWithBlock:^(NSArray *object, NSError *error){    NSString *abc = [object valueForKey:@"myKey"];
NSIndexPath = indexPath where cell.text = abc;

如果您以这种方式使用cellForItemAtIndexPath,那么您的代码将被致命地破坏。

单元格仅用于屏幕上的项目,当您滚动屏幕并从屏幕上删除或出现在屏幕上时,单元格可用于新项目。

如果索引路径不在屏幕上,UIView方法cellForItemAtIndexPath返回nil。如果你改变一个单元格的背景颜色,当其他项目在屏幕上移动时它会保持那个背景颜色,重复使用你刚刚设置的背景颜色的单元格。调试它时很有趣。

你修改单元格的地方是在UIViewController方法cellForItemAtIndexPath的实现中。

最新更新