简体   繁体   中英

How to convert value / string content of cell to nsindexpath

I have a UICollectionView which is populated with content from 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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