Pb graphic suite custom de cells dans UItableView quand ajout d'une UISearchBar

jejeadsljejeadsl Membre
03:33 modifié dans API UIKit #1
Bonjour à  tous et encore merci pour votre aide ,
Je rencontre un pb suite à  la customisation des cells dans une UITableView, quand j'ai ajouté une UISearchBar.
Ci dessous une vue sans Searchbar, donc pas de problème:
captureok.png

ici le pb rencontré suite ajout de la fameuse SearchBar :
capturenok.png

Voici le code du SearchRecipeBoxViewController.h
/////////////////////
#import <UIKit/UIKit.h>
#import <sqlite3.h> // Import the SQLite database framework

@interface SearchRecipeBoxViewController : UITableViewController <UISearchDisplayDelegate, UISearchBarDelegate> {
UIImageView *imageView;
NSMutableArray *listOfCategories;
// Database variables
NSString *databaseName;
NSString *databasePath;
NSString *QueryStr;
// Array to store the recipes objects
NSMutableArray *recipes;
NSMutableArray *filteredListContent; // The content filtered as a result of a search.

// The saved state of the search UI if a memory warning removed the view.
    NSString *savedSearchTerm;
    NSInteger savedScopeButtonIndex;
    BOOL searchWasActive;
}
- (void)checkAndCreateDatabase;
- (void)readRecipesFromDatabase;
@property (nonatomic, retain) IBOutlet UIImageView *imageView;
@property (nonatomic, retain) NSMutableArray *recipes;
@property (nonatomic, retain) NSString *QueryStr;
@property (nonatomic, retain) NSMutableArray *filteredListContent;
@property (nonatomic, copy) NSString *savedSearchTerm;
@property (nonatomic) NSInteger savedScopeButtonIndex;
@property (nonatomic) BOOL searchWasActive;
-(NSString*)produceImageReference:(NSString*) imgFileName withType:(NSString*) imgType;
@end




Voici le code du SearchRecipeBoxViewController.m

#import "SearchRecipeBoxViewController.h"
#import "AllRecipesFilterViewController.h"
#import "MyRecipeViewController.h"
#import "Real_Cajun_RecipesAppDelegate.h"
#import "Recipe.h" // Import the recipe object header
#define USE_CUSTOM_DRAWING 1

@implementation SearchRecipeBoxViewController
@synthesize recipes,QueryStr,imageView,filteredListContent, savedSearchTerm, savedScopeButtonIndex, searchWasActive;

#pragma mark -
#pragma mark Lifecycle methods

- (void)viewDidLoad {
    [super viewDidLoad];

//
// Change the properties of the imageView and tableView (these could be set
// in interface builder instead).
//
self.tableView.separatorStyle =  UITableViewCellSeparatorStyleSingleLine;//UITableViewCellSeparatorStyleNone;
self.tableView.rowHeight = 50;
//self.tableView.backgroundColor = [UIColor ClearColor];
imageView.image = [UIImage imageNamed:@gradientBackground.png];

QueryStr=@select * from recipes ORDER BY Title ASC ;

// Execute the "checkAndCreateDatabaseand" function
self.checkAndCreateDatabase;
// Query the database for all recipe records and construct the "recipes" array
self.readRecipesFromDatabase;


// create a filtered list that will contain products for the search results table.
self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.recipes count]];

// restore search settings if they were saved in didReceiveMemoryWarning.
    if (self.savedSearchTerm)
{
        [self.searchDisplayController setActive:self.searchWasActive];
        [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
        [self.searchDisplayController.searchBar setText:savedSearchTerm];
       
        self.savedSearchTerm = nil;
    }
[self.tableView reloadData];
self.tableView.scrollEnabled = YES;

}

-(void) checkAndCreateDatabase{
// Setup some globals
databaseName = @recipes.sql;

// Get the path to the documents directory and append the databaseTitle
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;

// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];

// If the database already exists then return without doing anything
if(success) return;

// If not then proceed to copy the database from the application to the users filesystem
// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];

[fileManager release];
}

-(void) readRecipesFromDatabase {

// Setup the database object
sqlite3 *database;

// Init the recipes Array
recipes = [[NSMutableArray alloc] init];

// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {

// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = [QueryStr UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aCategorie = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aSubmit = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *aMakes = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *aInfo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *aPrep_Time = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *aCook_Time = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
NSString *aReady_In = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
NSString *aIngredients = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];
NSString *aDirection = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 10)];
NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,11)];
NSString *aFavorites = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,12)];

// Create a new recipe object with the data from the database
Recipe *recipe = [[Recipe alloc] initWithTitle:aTitle Categorie:aCategorie  Submit:aSubmit Makes:aMakes Info:aInfo Prep_Time:aPrep_Time Cook_Time:aCook_Time Ready_In:aReady_In Ingredients:aIngredients Direction:aDirection Imageurl:aImageUrl Favorites:aFavorites];


// Add the recipe object to the recipes Array
[recipes addObject:recipe];


[recipe release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

}
sqlite3_close(database);
}


- (void)viewDidDisappear:(BOOL)animated
{
// save the state of the search UI so that it can be restored if the view is re-created
self.searchWasActive = [self.searchDisplayController isActive];
self.savedSearchTerm = [self.searchDisplayController.searchBar text];
self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
self.tableView.setNeedsDisplay; // repaint

}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}


- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
self.filteredListContent = nil;
}

#pragma mark Table view methods

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

#pragma mark -
#pragma mark UITableView data source and delegate methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
/*
If the requesting table view is the search display controller's table view, return the count of
    the filtered list, otherwise return the count of the main list.
*/
if (tableView == self.searchDisplayController.searchResultsTableView)


return [filteredListContent count];
    }
else
{
       
return [recipes count];
    }
}



// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        static NSString *CellIdentifier = @Cell;
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
#if USE_CUSTOM_DRAWING

//
// Create a background image view.
//
cell.backgroundView =
[[[UIImageView alloc] init] autorelease];
cell.selectedBackgroundView =
[[[UIImageView alloc] init] autorelease];
#endif
}
#if USE_CUSTOM_DRAWING
else
{
}

/*
If the requesting table view is the search display controller's table view, configure the cell using the filtered content, otherwise use the main list.
*/
Recipe *recipe = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
        recipe = [self.filteredListContent objectAtIndex:indexPath.row];

    }
else
{
        recipe = [self.recipes objectAtIndex:indexPath.row];

    }


    // Set up the cell...
//
// Set the background and selected background images for the text.
// Since we will round the corners at the top and bottom of sections, we
// need to conditionally choose the images based on the row index and the
// number of rows in the section.
//
UIImage *rowBackground;
UIImage *selectionBackground;
//bad name of png because bug with searcbar customize on standby
rowBackground = [UIImage imageNamed:@Row.png];//rowBackground = [UIImage imageNamed:@Row.png];
selectionBackground = [UIImage imageNamed:@RowSelected.png];

((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;

// use for determinated icon categorie and integrate it to the cell
Recipe *recipecat = (Recipe *)[recipes objectAtIndex:indexPath.row];
NSString *cellValue = recipecat.Categorie;
NSString *cat1 = @Appetizers & Beverages;
NSString *cat2= @Soups, Salads & Vegetables;
NSString *cat3 = @Side Dishes;
NSString *cat4 = @Main Dishes & Casseroles;
NSString *cat5 = @Breads & Rolls;
NSString *cat6 = @Pies, Pastries & Desserts;
NSString *cat7 = @Cakes, Cookies & Candy;
NSString *cat8 = @Jams and Jellies;
NSString *cat9 = @Nouveau Cajun;
NSString *cat10 = @Other;

if ([cellValue isEqualToString:cat1])
{
UIImage *image =[UIImage imageNamed:@iconappetizer.png];
cell.imageView.image =image;

}
else if ([cellValue isEqualToString:cat2])
{
UIImage *image =[UIImage imageNamed:@iconsalad.png];
cell.imageView.image =image;
}
else if ([cellValue isEqualToString:cat3])
{
UIImage *image =[UIImage imageNamed:@iconsides.png];
cell.imageView.image =image;
}
else if ([cellValue isEqualToString:cat4])
{
UIImage *image =[UIImage imageNamed:@iconmaindish.png];
cell.imageView.image =image;
}
else if ([cellValue isEqualToString:cat5])
{
UIImage *image =[UIImage imageNamed:@iconbread.png];
cell.imageView.image =image;
}
else if ([cellValue isEqualToString:cat6])
{
UIImage *image =[UIImage imageNamed:@icondessert.png];
cell.imageView.image =image;
}
else if ([cellValue isEqualToString:cat7])
{
UIImage *image =[UIImage imageNamed:@iconcake.png];
cell.imageView.image =image;
}
else if ([cellValue isEqualToString:cat8])
{
UIImage *image =[UIImage imageNamed:@iconjams.png];
cell.imageView.image =image;
}
else if ([cellValue isEqualToString:cat9])
{
UIImage *image =[UIImage imageNamed:@iconstar.png];
cell.imageView.image =image;
}
else if ([cellValue isEqualToString:cat10])
{
UIImage *image =[UIImage imageNamed:@iconother.png];
cell.imageView.image =image;
}

// Set up the cell
//Recipe *recipe = (Recipe *)[recipes objectAtIndex:indexPath.row];
cell.textLabel.text = recipe.Title;
[cell.textLabel setFont:[UIFont boldSystemFontOfSize: 17]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
#else
cell.text = [NSString stringWithFormat:@Cell at row %ld., [indexPath row]];
#endif

return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
MyRecipeViewController *mrvc = MyRecipeViewController alloc] initWithNibName:@&quot;MyRecipeView&quot; bundle:[NSBundle mainBundle;
[self.navigationController pushViewController:mrvc animated:YES];

/*
If the requesting table view is the search display controller's table view, configure the next view controller using the filtered content, otherwise use the main list.
*/
Recipe *recipe = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
recipe = [self.filteredListContent objectAtIndex:indexPath.row];

    }
else
{
        recipe = [self.recipes objectAtIndex:indexPath.row];

    }
mrvc.title= recipe.Title;
mrvc.ImgNameStr= recipe.Imageurl;
if ([mrvc.ImgNameStr isEqualToString :@realcajun])
{}
else if (mrvc.ImgNameStr != nil) {
UIBarButtonItem * rightButton = [[UIBarButtonItem alloc]
initWithTitle:@Photo style:UIBarButtonItemStyleDone target:mrvc action:@selector(photoButtonTapped)];
mrvc.navigationItem.rightBarButtonItem = rightButton; [rightButton release];
}

NSMutableString *htmlContents = [[NSMutableString alloc] initWithCapacity:1000]; ;
[htmlContents appendString: @<;html><head><style type='text/css'>.Style5 {font-family: Verdana, Arial, Helvetica, sans-serif;font-size: 14px;}\
.Style6 {font-family: Verdana, Arial, Helvetica, sans-serif;font-size: 14px;font-weight: bold;color: #7CA072;}.Style9 \
{font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 14px; font-style: italic; }.Style11 {font-family: Verdana, \
Arial, Helvetica, sans-serif; font-size: 18px; font-weight: bold; color: #7CA072; }.Style12 {font-size: 12px}</style></head>\
<body><table border='0'><tr><td valign='top'><p align='center' class='Style5'><span class='Style11'>"];
[htmlContents appendString:[recipe Title]];
[htmlContents appendString:@</span><br /><span class='Style12'>];
[htmlContents appendString:[recipe Categorie]];
[htmlContents appendString:@</span><br /><span class='Style12'><strong>Submitted by ];
[htmlContents appendString:[recipe Submit]];
[htmlContents appendString:@</strong></span> <br /><br /></span>];
[htmlContents appendString:[self produceImageReference: [NSString stringWithFormat:@%@%@", @p,[recipe Imageurl]] withType:@jpg]];
[htmlContents appendString:@</p><p class='Style5'><strong>Makes: </strong>];
[htmlContents appendString:[recipe Makes]];
[htmlContents appendString:@<br /><strong>Prep Time: </strong>];
[htmlContents appendString:[recipe Prep_Time]];
[htmlContents appendString:@<br /><strong>Cook Time: </strong>];
[htmlContents appendString:[recipe Cook_Time]];
[htmlContents appendString:@<br /><strong>Ready In: </strong>];
[htmlContents appendString:[recipe Ready_In]];
[htmlContents appendString:@</p><p align='justify' class='Style9'>];
[htmlContents appendString:[recipe Info]];
[htmlContents appendString:@</p><p align='justify' class='Style5'><span class='Style6'>Ingredients</span><br />];
[htmlContents appendString:[recipe Ingredients]];
[htmlContents appendString:@</p><p align='justify' class='Style5'><span class='Style6'>Direction</span><br />];
[htmlContents appendString:[recipe Direction]];
[htmlContents appendString:@</body></html>];
[htmlContents appendString:@</p><p class='Style5'>&nbsp;</p><br><br><br></td></tr></table></body></html>];
[mrvc.webView loadHTMLString:htmlContents baseURL:nil];
[htmlContents release];
[mrvc release];
}

#pragma mark -
#pragma mark Content Filtering

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
/*
Update the filtered array based on the search text and scope.
*/

[self.filteredListContent removeAllObjects]; // First clear the filtered array.


/*
Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
*/
for (Recipe *recipe in recipes)
{
NSComparisonResult result = [recipe.Title compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
            if (result == NSOrderedSame)
{
[self.filteredListContent addObject:recipe];

            }

}
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:
self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex];
        return YES;
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption;
    return YES;
}

-(NSString*)produceImageReference:(NSString*) imgFileName withType:(NSString*) imgType{
NSMutableString *returnString = [[[NSMutableString alloc] initWithCapacity:100] autorelease];
NSString *filePath =[[NSBundle mainBundle] pathForResource:imgFileName ofType:imgType];
if(filePath){
[returnString appendString:@<IMG SRC=\file://"];
[returnString appendString:filePath];
[returnString appendString:@\ ALT=\""];
[returnString appendString:imgFileName];
[returnString appendString:@\>"];
return returnString;
} else return @";";
}

- (void)dealloc {
[listOfCategories release];
[recipes release];
[QueryStr release];
[imageView release];
[filteredListContent release];
[super dealloc];
}
@end
///////////////////


JE SUIS PRENEUR DE TOUTES INFOS QUI POURRAIENT M'AIDER, CAR LA JE BUTE PROFONDEMENT. JE PENSE MEME SUPPRIMER LA PERSONNALISATION DES CELLS.

MERCI POUR VOTRE AIDE

JEJEADSL
Connectez-vous ou Inscrivez-vous pour répondre.