Search code examples
iosobjective-cuitableviewnsfilemanager

Show a cell.button only if file exists


I have a table view with some cells populated by 2 labels.
If an mp3 file named "label1-label2-name" exists, I play the file.

 NSArray *final;
 NSString *element;
 final = [NSArray arrayWithObjects: @"a", @"b", @"c", @"d", nil];

Now in my cellForRowAtIndexPath I'm trying to do the same, but just to show the play button if the file exists (button is initially hidden).

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

 for (element in final) {

    buttonA = [NSString stringWithFormat:@"%@-%@-AAA-%@", current[indexPath.row][0],current[indexPath.row][1], element];
    fileA = [[NSBundle mainBundle] pathForResource:buttonA ofType:@"mp3"];
    BOOL fileExistsA = [[NSFileManager defaultManager] fileExistsAtPath:fileA];

    if (fileExistsA) {

        cell.playA.hidden = false;

    }
 }
}

What's happening here is that even if a file named "label1-label-2-AAA-a" exists, if the file "label1-label-2-AAA-d" doesn't, the play button will be hidden.

How to show/hide the play at specific cells?


Solution

  • It is not clear from the code snippet you've shared if you are reusing cells or not, but assuming you are, you may want to update the cell.playA.hidden state in both cases (e.g. if the file exists or not), otherwise you won't see the "play" button once a cell with a existent mp3 file appears on screen, and, while configuring it, you dequeue a cell with a previously hidden button.

    - (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        /// Get the cell
    
        cell.playA.hidden = true;
        for (element in final) {
            buttonA = [NSString stringWithFormat:@"%@-%@-AAA-%@", current[indexPath.row][0],current[indexPath.row][1], element];
            fileA = [[NSBundle mainBundle] pathForResource:buttonA ofType:@"mp3"];
            BOOL fileExistsA = [[NSFileManager defaultManager] fileExistsAtPath:fileA];
            if (fileExistsA) {
                cell.playA.hidden = false;
                break;
            }
        }
    }
    

    Assuming it is what you want, we check all possible filenames for this cell ("label1-label-2-AAA-a", "label1-label-2-AAA-b", ...), and if at least one is present, we show the button, otherwise we hide it.