簡體   English   中英

如何從Xcode中的篩選數組創建表視圖控制器?

[英]How to create table view controller from filtered arrays in Xcode?

我目前有2個表視圖。 一個是基本的,可以顯示每個單元格,如果選中,它會導航到詳細視圖控制器。

我創建了一個新的ViewController來創建過濾的頁面視圖。 我用plist填充頁面視圖。 我設法創建了一個過濾器,但是我不知道如何從這里繼續。

這是我的代碼:

- (IBAction)ingredientsAddButton:(UIButton *)sender 
{
    int j=0;
    onemsiz.text=ingredientTextField.text;
    ingredientText=onemsiz.text;
    NSLog(ingredientText);
    NSString *path = [[NSBundle mainBundle] pathForResource:@"recipes" ofType:@"plist"];
    NSArray *arrayOfPlist = [[NSArray alloc] initWithContentsOfFile:path];
    if (arrayOfPlist==NULL) {

    }else {
        for (int i=0; i<4; i++) { 
            // i currently have 4 element is plist.
            NSString *strCurrentRecipeIngredients = [[arrayOfPlist objectAtIndex:i] objectForKey:@"recipeIngredients"];
            NSString *strCurrentRecipeName = [[arrayOfPlist objectAtIndex:i] objectForKey:@"recipeName"];
            //NSLog(@"%d. Loop \n", i+1);
            if([strCurrentRecipeIngredients rangeOfString:(@"%@",ingredientText)].location!=NSNotFound)
            {
                NSLog(@"%@ contains %@ ",strCurrentRecipeName, ingredientText);
                NSLog(ingredientText);
                NSLog(strCurrentRecipeIngredients);
                j++;
            }else {
                NSLog(@"Not found");
                NSLog(ingredientText);
                NSLog(strCurrentRecipeIngredients);
            }
            if (ingredientText==NULL) {
                NSLog(@"empty input");
            }else {

            }
        }
    }
    NSLog(@"%d",j);
}

我的第一個問題是如何在表格視圖中顯示結果? 如果需要,我可以提供一些屏幕截圖。

您可以添加bool ivar來告訴您何時需要顯示過濾后的數組,並添加新的數組來顯示過濾后的數據:

BOOL isShowFilteredData;
NSArray *filteredData;

在init或viewDidLoad中,將bool初始化為false(您不想顯示所有數據);

isShowFilteredData = NO;

您必須更改數據源/委托方法以使用正確的數據:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return isShowFilteredData ? isShowFilteredData.count : myDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //configure cell, etc..
    //your code 
    if (isShowFilteredData) 
    {
         // show filtered data
         id obj = filteredData[indexPath.row];
         // do something with result
    }
    else
    {
        // show all data
    }
}

現在,當您想顯示過濾后的數據時,只需將ivar更改為true,即可初始化filteredData數組並用要顯示的數據填充它,然后調用reloadData:

isShowFilteredData = YES;
filteredData = [[NSArray alloc] initWithObjects:.....];
[self.tableView reloadData];

但是,如果要顯示所有數據,請執行以下操作:

isShowFilteredData = NO;
[self.tableView reloadData];

這只是您可以使用的解決方案之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM