简体   繁体   English

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

[英]How to convert value / string content of cell to nsindexpath

I have a UICollectionView which is populated with content from CoreData. 我有一个UICollectionView,其中填充了CoreData中的内容。 When the view loads I want to preselect/highlight some of the cells. 当视图加载时,我想预选/突出显示某些单元格。

I have been able to get the items preselected using the code below. 我已经可以使用以下代码预先选择商品。 The highlighting isn't working as seamlessly as I would like, but I can make it work. 突出显示的效果不尽如人意,但我可以使其正常工作。

- (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);
    }
}

I DO NOT want to have the preselects hardcoded however. 我不想对预选进行硬编码。 I want to do something like: 我想做类似的事情:

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

or better yet 或更好

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

If you use cellForItemAtIndexPath that way, then your code is fatally broken. 如果您以这种方式使用cellForItemAtIndexPath,那么您的代码将被致命破坏。

cells only exist for items on the screen, and as you scroll around and items are removed from the screen or appear on the screen, cells are reused for new items. 单元格仅适用于屏幕上的项目,并且当您滚动浏览并且项目从屏幕上删除或出现在屏幕上时,单元格将被重新用于新项目。

The UIView method cellForItemAtIndexPath returns nil if the index path is not on the screen. 如果索引路径不在屏幕上,则UIView方法cellForItemAtIndexPath返回nil。 And if you change the background colour of a cell, then it keeps that background colour as it other items move on the screen, reusing the cell with the background colour that you just set. 而且,如果您更改单元格的背景色,则它将保留背景色,因为其他项目在屏幕上移动,并以您刚设置的背景色重新使用该单元格。 Good fun when you debug it. 调试时很好玩。

The place where you modify the cells is in your implementation of the UIViewController method cellForItemAtIndexPath. 修改单元格的位置在UIViewController方法cellForItemAtIndexPath的实现中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM