I use the following method to present a UIViewController named DictAddSubSecondCell:
// UIViewControler 1
- (IBAction)addWord:(id)sender{
dictAddSubSecondCellController = [[DictAddSubSecondCell alloc] initWithNibName:#"DictAddSubSecondCell" bundle:nil];
[self presentModalViewController:dictAddSubSecondCellController animated:YES];
[dictAddSubSecondCellController release];
}
and when I click the button in DictAddSubSecondCell:
- (IBAction)dismissAction:(id)sender{
[self dismissModalViewControllerAnimated:YES];
}
the tableView at UIViewControler 1 didn't reload it's data, but I added a method in viewWillApear method:
[self.table reloadData];
but it still not work. I have no idea about this. Is there any suggestions for me? thanks.
Here is the full source code of UIViewcontroller 1:
//
// DictAddSubSecond.m
//
// Created by Samuel Armstrong on 4/8/12.
// Copyright 2012 __MyCompanyName__. All rights reserved.
//
#import "DictAddSubSecond.h"
#import "DictionaryList.h"
#implementation DictAddSubSecond
#synthesize dictList, table, editButton;
#synthesize dictAddSubSecondCellController;
- (IBAction)addWord:(id)sender
{
dictAddSubSecondCellController = [[DictAddSubSecondCell alloc] initWithNibName:#"DictAddSubSecondCell" bundle:nil];
[self presentModalViewController:dictAddSubSecondCellController animated:YES];
[dictAddSubSecondCellController release];
}
- (IBAction)toggleEdit {
[self.table setEditing:!self.table.editing animated:YES];
if (self.table.editing) {
[editButton setTitle:#"Done"];
[editButton setStyle:UIBarButtonItemStyleDone];
}
else {
[editButton setTitle:#"Edit"];
[editButton setStyle:UIBarButtonItemStyleBordered];
}
}
- (IBAction)dismissAction:(id)sender
{
[self dismissModalViewControllerAnimated:NO];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)refreshTableData
{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *file = [path stringByAppendingPathComponent:#"dictWithWords.tmp"];
if (dictList == nil) {
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:file];
if ([array objectAtIndex:0] != nil) {
dictList = [[NSMutableArray alloc] initWithCapacity:1];
self.dictList = array;
[array release];
}
else
{
dictList = [[NSMutableArray alloc] initWithCapacity:1];
}
}
[self.table reloadData];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self refreshTableData];
}
- (void)someMethodToReloadTable:(NSNotification *)notification
{
[table reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(someMethodToReloadTable) name:#"reloadTable" object:nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"reloadTable" object:nil];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dictList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MoveMeCellIdentifier = #"MoveMeCellIdentifier";
UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:MoveMeCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MoveMeCellIdentifier] autorelease];
//A Boolean value that determines whether the cell shows the reordering control.
cell.showsReorderControl = YES;
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [dictList objectAtIndex:row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark -
#pragma mark Table View Delegate Methods
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
[self.dictList removeObjectAtIndex:row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationMiddle];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
// Asks the data source whether a given row can be moved to another location in the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
//Tells the data source to move a row at a specific location in the table view to another location.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
NSUInteger fromRow = [fromIndexPath row];
NSUInteger toRow = [toIndexPath row];
id object = [[dictList objectAtIndex:fromRow] retain];
[dictList removeObjectAtIndex:fromRow];
[dictList insertObject:object atIndex:toRow];
[object release];
}
#end
Try calling it in viewDidAppear: instead of viewWillAppear:.
Related
In my app I have a popup with a [table view][1] .
When compiled with Xcode 5.1 everything works fine, but the same code compiled with Xcode 6.1 failed to call the [cellForRowAtIndexPath][3] [delegate][4] method.
The other delegate meths are called.
One intersting point is self.tableView.rowHeight; returns -1
I have tried explicitly setting the delegate and data source to self but that makes not difference
The class is called by the following code;
`-(IBAction)selectLanguage:(id)sender
{
ATLMLanguagePopoverTableViewController *pvc = [[ATLMLanguagePopoverTableViewController alloc] initWithNibName:nil bundle:nil];
pvc.target = self;
pvc.action = #selector(popoverDidSelectItem:);
pvc.items = [[[ATLMLibraryManager getManager]libraryDefaults]getAvailableLanguageNames];
_myPopoverController.contentViewController = pvc;
[_myPopoverController setPopoverContentSize:[pvc popoverContentSize]];
[_myPopoverController presentPopoverFromBarButtonItem:(UIBarButtonItem *)sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
`
Hear is the definition of the class
/
/ LanguagePopoverTableViewController.m
// SalesAid
//
// Created by phuang on 1/16/13.
// Copyright (c) 2013 Align Technology. All rights reserved.
//
#import "ATLMLanguagePopoverTableViewController.h"
#import "ATLMLocalizationManager.h"
#import "ATLMUtils.h"
#interface ATLMLanguagePopoverTableViewController ()
#end
#implementation ATLMLanguagePopoverTableViewController
#synthesize items, selectedItem, target, action;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
selectedItem = -1;
target = nil;
action = NULL;
}
return self;
}
-(void) resetLocalization {
[self.tableView reloadData];
}
- (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)setItems:(NSArray *)newItems {
items = [newItems copy];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
selectedItem=0;
NSString *curLang = (NSString *) [[ATLMLocalizationManager getManager]getCurrentLanguage] ;
for(int i = 0; i < items.count ; i++ ){
if([curLang isEqualToString:(NSString *)[items objectAtIndex:i]]){
selectedItem = i;
break;
}
}
NSIndexPath *i = [NSIndexPath indexPathForRow:selectedItem inSection:0];
[self.tableView selectRowAtIndexPath:i animated:NO scrollPosition:UITableViewScrollPositionNone];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (CGSize)popoverContentSize {
NSInteger rowHeight = self.tableView.rowHeight;
UITableView *tv = self.tableView;
rowHeight = 50;
return CGSizeMake(100, [items count] * rowHeight);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.font = [UIFont systemFontOfSize:14];
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [ATLMUtils getAlignBlue];
cell.selectedBackgroundView = myBackView;
[cell setSelectedBackgroundView: myBackView ];
NSString *textLabelKey = [items objectAtIndex:[indexPath indexAtPosition:1]];
cell.textLabel.text = ATLMLocalizedString(textLabelKey, nil);
cell.textLabel.textAlignment = NSTextAlignmentCenter;
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
selectedItem = indexPath.row;
if (target != nil && action != NULL) {
[target performSelector:action withObject:self];
}
}
#end
`
OK to answer my own question;
Basically the code adds the model to the view controller after the init method is called. However is seem the thread model has changed a bit and the view is created before the model is added so the row count in the model is zero
The solution is to pass the model as part of the init method.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil items:(NSArray *)itemArray
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
items = [itemArray copy];
selectedItem = -1;
target = nil;
action = nil;
}
return self;
}
I'm seeing some strange behaviour with my UItableViewController shown using Popover.
This is my ViewController code:
#interface PrepareViewController ()
{
NSMutableArray *_objects;
NSString *savingKey;
}
#end
#implementation PrepareViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)awakeFromNib
{
self.clearsSelectionOnViewWillAppear = NO;
self.preferredContentSize = CGSizeMake(320.0, 600.0);
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
// Register a class or nib file using registerNib:forCellReuseIdentifier
// o registerClass:forCellReuiseIdentifier: method before calling this method
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
// Setup savingKey
savingKey = #"prepareKey";
// Load the items from NSUserDefaults
_objects = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:savingKey]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(defaultsChanged:) name:NSUserDefaultsDidChangeNotification object:nil];
}
- (void)defaultsChanged:(NSNotification *)notification {
// Setup savingKey
savingKey = #"prepareKey";
// Load the items from NSUserDefaults
_objects = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:savingKey]];
// Reload the tableView
[self.tableView reloadData];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)saveSummaries {
// Save the summaries to NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:_objects forKey:savingKey];
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _objects.count;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *object = _objects[indexPath.row];
cell.textLabel.text = [object description];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Open the chosen item
MyManager *sharedManager = [MyManager sharedManager];
sharedManager.openSummary = _objects[indexPath.row];
// Modal to SummaryViewController
[self performSegueWithIdentifier:#"summarySegue" sender:self];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
// Delete the associated information
[[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:#"%#%#", _objects[indexPath.row], #"-summary"]];
NSLog(#"delete3");
// Save the new list of combined summaries
[[NSUserDefaults standardUserDefaults] setObject:_objects forKey:#"prepareKey"];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
#end
Problem:
When the user taps delete while in edit mode, no animation appears and the selected item snaps back into place without any animation and the item remains undeleted. I've checked that the delete method gets called - any idea what could be the problem?
Thanks for help!
I think it's because of this:
- (void)defaultsChanged:(NSNotification *)notification {
// Setup savingKey
savingKey = #"prepareKey";
// Load the items from NSUserDefaults
_objects = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:savingKey]];
// Reload the tableView
[self.tableView reloadData]; <------- manual reload without animations
}
When you change defaults in:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
that code is executed.
I'm creating an iphone app using storyboard. I'm basically new on objective c and Xcode.
I have a list of categories, every time I click on a category it should open a tableView, so I can add an item in that category. But instead of getting a different tableView for each category, its the same table for all the categories and the added items are copied.
How can I create a new table for each label?
Thanks in advance!
Here's what I have for adding a category
#interface ListViewController ()
#end
#implementation ListViewController{
NSMutableArray *items;
}
#synthesize lists;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
items = [NSMutableArray arrayWithCapacity:20];
List *item = [[List alloc] init];
item.title = #"Grocery List";
[items addObject:item];
item = [[List alloc]init];
item.title = #"Project List";
[items addObject:item];
item = [[List alloc] init];
item.title = #"Events List";
[items addObject:item];
self.lists = items;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [self.lists count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Configure the cell...
/*UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ListsCell"];
List *list = [self.lists objectAtIndex:indexPath.row];
cell.textLabel.text = list.title;*/
ListCell *cell = (ListCell *)[tableView dequeueReusableCellWithIdentifier:#"ListsCell"];
List *list = [self.lists objectAtIndex:indexPath.row];
cell.titleLabel.text = list.title;
return cell;
}
//Add new list, new row will be added on the bottom and its data source must always be sync
-(void)addViewControllerSave:(AddViewController *)controller addList:(List *)list{
[self.lists addObject:list];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.lists count] - 1 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self dismissViewControllerAnimated:YES completion:nil];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
if(editingStyle == UITableViewCellEditingStyleDelete){
[self.lists removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
/* else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}*/
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
/*
#pragma mark - Navigation
*/
// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if([segue.identifier isEqualToString:#"AddList"]){
UINavigationController *navigationController = segue.destinationViewController;
AddViewController *addViewController = [[navigationController viewControllers] objectAtIndex:0];
addViewController.delegate = self;
}
else if([segue.identifier isEqualToString:#"ViewItem"]){
UINavigationController *nav = segue.destinationViewController;
ItemViewController *itemViewController = [[nav viewControllers] objectAtIndex:0];
itemViewController.delegate = self;
}
}
#pragma mark - AddViewControllerDelegate
-(void)addViewControllerCancel:(AddViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)addViewControllerSave:(AddViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)itemViewControllerBack:(ItemViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Here's what I have for adding an item:
#interface ItemViewController ()
#end
#implementation ItemViewController{
NSMutableArray *newItems;
}
#synthesize items;
#synthesize delegate;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
newItems = [NSMutableArray arrayWithCapacity:20];
Item *i = [[Item alloc]init];
i.listItem = #"a";
[newItems addObject:i];
self.items = newItems;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Configure the cell...
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ItemsCell"];
Item *item = [self.items objectAtIndex:indexPath.row];
cell.textLabel.text = item.listItem;
return cell;
}
-(void)addIteViewControllerSave:(AddItemViewController *)controller addItem:(Item *)item{
[self.items addObject:item];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.items count] -1 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - Navigation
// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if([segue.identifier isEqualToString:#"AddItem"]){
UINavigationController *navigationController = segue.destinationViewController;
AddItemViewController *addItemViewController = [[navigationController viewControllers]objectAtIndex:0];
addItemViewController.itemDelegate = self;
}
}
#pragma mark - AddItemViewControllerDelegate
-(void)addItemviewControllerCancel:(AddItemViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)addIteViewControllerSave:(AddItemViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - ItemViewControllerDelegate
-(IBAction)back:(id)sender{
[self.delegate itemViewControllerBack:self];
}
#end
AddItemViewController
#import "AddItemViewController.h"
#import "Item.h"
#interface AddItemViewController ()
#end
#implementation AddItemViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)cancel:(id)sender{
[self.itemDelegate addItemviewControllerCancel:self];
}
-(IBAction)save:(id)sender{
Item *item = [[Item alloc] init];
item.listItem = self.listItemTextField.text;
[self.itemDelegate addIteViewControllerSave:self addItem:item];
}
#end
Don't create a new table view for each label, instead populate it with different data for each label, you will need to change the object you are storing your data in and call
[tableView reloadData];
If all the added items you may need to clear out your array you are using to store the objects before adding the additional content.
[self.items removeAllObjects];
I created a subClass of UITextView with a searchBar, here is the code:
#import "SezioniTableController.h"
#interface SezioniTableController ()
#end
#implementation SezioniTableController
#synthesize searchBar,searchDisplayController;
#synthesize arraySezioni,arrayFiltrato;
#synthesize objTesto;
- (id)initWithStyle:(UITableViewStyle)style andArray:(NSMutableArray *)array{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
self.searchBar.delegate = self;
self.searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchDisplayController.delegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.arraySezioni = array;
self.arrayFiltrato = array;
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) loadView {}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.arrayFiltrato.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:#"MyIdentifier"];
}
self.objTesto = [arrayFiltrato objectAtIndex:indexPath.row];
cell.textLabel.text = self.objTesto.titoloTesto;
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
NSDictionary *dict = [NSDictionary dictionaryWithObject:[self.arrayFiltrato objectAtIndex:indexPath.row] forKey:#"Testo"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"PassaggioTesto" object:self userInfo:dict];
NSLog(#"Click");
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
return self.searchBar; //in .h, IBOutlet UISearchBar* search;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 44;
}
- (BOOL) searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[self filterContentForSearchText:searchString scope: [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
NSLog(#"aa");
//[[NSNotificationCenter defaultCenter] postNotificationName:#"ReloadTable" object:self];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL) searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
NSLog(#"ab");
//[[NSNotificationCenter defaultCenter] postNotificationName:#"ReloadTable" object:self];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void) filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
NSLog(#"a count:%d",self.arraySezioni.count);
[self.arrayFiltrato removeAllObjects]; // First clear the filtered array.
for (objTesto in self.arraySezioni){
NSComparisonResult result = [objTesto.titoloTesto compare:searchText options:NSCaseInsensitiveSearch range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame){
NSLog(#"Titolo: %#",objTesto.titoloTesto);
[self.arrayFiltrato addObject:self.objTesto];
}else{
NSLog(#"Non trovato");
}
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)saearchBar {
[self.arrayFiltrato removeAllObjects];
[self.arrayFiltrato addObjectsFromArray: self.arraySezioni];
}
#end
On my uiviewcontroller I create a table using the uitableview created with this code:
self.arrayTesti = [self.dataLoad leggiArgomentiDellaSezione:tag];
self.table = [[SezioniTableController alloc] initWithStyle:UITableViewStylePlain andArray:self.arrayTesti];
self.tableArgumentView.delegate = self.table;
self.tableArgumentView.dataSource = self.table;
[self.tableArgumentView reloadData];
The viewcontroller is for an iPad application, the table works perfectly but if I try to search something it doesn't work!
Can you help me?
If you assign
self.arraySezioni = array;
self.arrayFiltrato = array;
then both self.arraySezioni and self.arrayFiltrato are pointers to the same array. Which means that if you empty one array with
[self.arrayFiltrato removeAllObjects];
then the other array self.arraySezioni (and the original array) are also empty.
So at least self.arrayFiltrato should be a copy of the original array:
self.arrayFiltrato = [array copy];
I was wondering why this code would give me black UITableViewCells when I set the selected property ON. If I do that, the content of the cell turns completely black, and I have no idea why.
Here's the code
//
// TableViewAdapter.m
// TableviewScanMode
//
// Created by Nick Overdijk on 8/26/10.
// Copyright 2010 Nick Overdijk. All rights reserved.
//
#import "TableViewAdapter.h"
#import "Model.h"
#implementation TableViewAdapter
#synthesize model;
- (id) initWithModel: (Model*) model {
self = [super init];
if(self != nil){
self->model = [model retain];
}
return self;
}
- (void) dealloc {
[model release];
[super dealloc];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[model cellData] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[[model cellData] objectAtIndex: section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [[[model cellData] objectAtIndex: indexPath.section] objectAtIndex: indexPath.row];
if(indexPath.row == [[model currentSelected] row] && indexPath.section == [[model currentSelected] section]){
cell.selected = YES;
} else {
cell.selected = NO;
}
return cell;
}
#end
//
// RootViewController.m
// TableviewScanMode
//
// Created by Nick Overdijk on 8/24/10.
// Copyright Nick Overdijk 2010. All rights reserved.
//
#import "RootViewController.h"
#import "Model.h"
#import "TableViewAdapter.h"
#implementation RootViewController
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
model = [[Model alloc] init];
[model addObserver:self
forKeyPath:#"updatedIndexPaths"
options:NSKeyValueObservingOptionNew
context:NULL
];
[model startSelectionRotation];
adapter = [[TableViewAdapter alloc] initWithModel: model];
self.tableView.dataSource = adapter;
[super viewDidLoad];
}
- (void)dealloc {
[adapter release];
[model release];
[super dealloc];
}
#pragma mark -
#pragma mark KVO updates
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSArray * reloadThese = [change objectForKey: NSKeyValueChangeNewKey];
[self.tableView reloadRowsAtIndexPaths: reloadThese withRowAnimation: UITableViewRowAnimationFade];
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
#end
If you need more code, shout. :)
Many thanks in advance,
Nick
I was having the same problem and fixed it by moving the cell.selected = YES into tableView:willDisplayCell:forRowAtIndexPath instead.
I think it might be related to the note at the bottom of the UITableViewCell docs about changes to background color requiring use of tableView:willDisplayCell:forRowAtIndexPath (presumably selected sets the background color).