【问题标题】:Show a cell.button only if file exists仅当文件存在时才显示 cell.button
【发布时间】:2016-09-11 08:10:26
【问题描述】:

我有一个表格视图,其中一些单元格由 2 个标签填充。
如果存在名为“label1-label2-name”的 mp3 文件,则播放该文件。

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

现在在我的cellForRowAtIndexPath 中,我正在尝试做同样的事情,但只是在文件存在时显示播放按钮(按钮最初是隐藏的)。

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

    }
 }
}

这里发生的情况是,即使存在名为“label1-label-2-AAA-a”的文件,如果文件“label1-label-2-AAA-d”不存在,播放按钮将被隐藏.

如何在特定单元格显示/隐藏播放?

【问题讨论】:

    标签: ios objective-c uitableview nsfilemanager


    【解决方案1】:

    您共享的代码 sn-p 不清楚您是否正在重用单元格,但假设您是,您可能希望在这两种情况下更新 cell.playA.hidden 状态(例如,如果文件存在或不是),否则一旦屏幕上出现具有现有 mp3 文件的单元格,您将看不到“播放”按钮,并且在配置它时,您将具有先前隐藏按钮的单元格出列。

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

    假设这是您想要的,我们会检查此单元格的所有可能文件名 ("label1-label-2-AAA-a", "label1 -label-2-AAA-b", ...),如果存在至少一个,我们显示按钮,否则我们隐藏它.

    【讨论】:

    • 这样吗? cell.playA.hidden = !fileExistsA; 然后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]; }
    • 抱歉,我误读了您的问题 — 我没有意识到您在 cellForRowAtIndexPath 中循环浏览 final。我已经更新了我的答案。
    • @rmaddy 不,不会,我一直牢记单元格的重复使用。请再次执行该方法:初始问题中的代码循环遍历数组以找到至少一个现有文件。所以我先重置hidden属性,如果我们找到至少一个,然后将其设置为true
    • @AlexStaravoitau 哎呀。我确实忽略了第一行。对此感到抱歉。
    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 2014-09-05
    • 2016-09-05
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多