本文介绍了Objective-C:如何为 UiTableView 中的每个文件名添加一个新单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我有一些代码列出了保存我的视频文件的文档目录的路径.然后代码在一个单元格中列出它,但它是完整路径并且只使用一个单元格.所以我想要做的是首先切断路径,只在文档目录中列出文件的文件名,然后为每个文件设置一个单独的单元格.这可能吗?

Bellow i have some code that lists the path to the documents directory where my video files are saved. The code then lists that in a cell but it's the full path and only one cell is used. So what i want to do is first cut down the path and only list the file name of the file in the documents director and then have an individual cell for each file. Is that possible?

这是我用来列出文档目录路径的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];


}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(!filePathsArray)  // if data loading has been completed, return the number of rows ELSE return 1
    {

        if ([filePathsArray count] > 0)
            return [filePathsArray count];
        else
            return 1;
    }

    return 1;
}


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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
    cell.textLabel.text = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]];
    return cell;
}

提前致谢.

推荐答案

就像现在一样,您每次在 viewDidLoad 中加载文件路径tableView:cellForRowAtIndexPath: 被调用,这是低效且不必要的.

As it is now, you're loading the file paths in viewDidLoad and each time the method tableView:cellForRowAtIndexPath: is called which is inefficient and unnecessary.

无论如何,你只想要这样的东西:

In any case, you just want something like:

cell.textLabel.text = [filePathsArray[indexPath.row] lastPathComponent];

如果我正确理解您的要求.

if I understand your requirements correctly.

这篇关于Objective-C:如何为 UiTableView 中的每个文件名添加一个新单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 14:33