Soheil Novinfard Soheil Novinfard - 3 months ago 12
Objective-C Question

Scroll to specific cell in UITableView with cell property

I have an example of

UITableViewCell
as below:

//
// ItemTableViewCell.h
//
#import <UIKit/UIKit.h>

@interface ItemTableViewCell : UITableViewCell

@property (weak, nonatomic) NSString *itemId;

@end


In my
UIViewController
with
UITableView
I have the below assigning :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

NSManagedObject *row = [self.itemsFRC objectAtIndexPath:indexPath];
ItemTableViewCell *cell = (ItemTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:@"cellId" forIndexPath:indexPath];

cell.itemId = [row valueForKey:@"item_id"];
}


Now, how can I scroll to specific cell in
UITableView
with it's cell property
itemId
?

Note: I highly prefer to not to use
indexPathForRow
method.

Answer

You should do the following:

  1. Find NSManagedObject by item_id
  2. Get indexPath of found object from NSFetchedResultsController
  3. Scroll tableView to that indexPath

See code example below:

- (void) scrollToRowWithItemID: (NSString *) itemID {
    NSArray *fetchedObjects = self.itemsFRC.fetchedObjects;
    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"item_id == %@", itemID];
    NSArray *filteredArray = [fetchedObjects filteredArrayUsingPredicate: predicate];
    NSIndexPath *indexPath = [self.itemsFRC indexPathForObject: filteredArray.firstObject];
    [self.tableView scrollToRowAtIndexPath: indexPath atScrollPosition: UITableViewScrollPositionNone animated: true];   
}