I have a searchDisplayController that searches a UITableView.
After entering the search terms, I can see another UITableView that contains the search results. However, I want this UITableView to be GROUPED, not PLAIN (like it is by default).
How do I do this?
This worked for me (iOS 5.0):
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
[self.searchController setValue:[NSNumber numberWithInt:UITableViewStyleGrouped]
forKey:#"_searchResultsTableViewStyle"];
If - like me - you think the plain TableView was way too ugly, you can also abandon the use of SearchDisplayController.
I just:
inserted in an empty View a searchBar and a TableView as we usually do for IBOutlet
selected the File's owner as delegate for both of them.
At the beginin the number of section is 0 ([myTab count]) then I used reloadData and this time myTab is populated by the result.
[self.resultTableView reloadData];
Here you can find all the method I used from the delegates
#interface MyViewController : UIViewController <UIApplicationDelegate, UISearchBarDelegate> {
IBOutlet UISearchBar *searchBar;
IBOutlet UITableView *resultTableView;
}
#property (nonatomic, retain) IBOutlet UISearchBar *searchBar;
#property (nonatomic, retain) IBOutlet UITableView *resultTableView;
//For your searchBar the 2 most important methods are
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBarClicked;
- (BOOL)searchBarTextDidEndEditing;
//For your TableView the most important methods are in my case:
//number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
//HEADERS
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
//different numbers of row by section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
//the cells themselves
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
#end
After all, the simplest solution is often the best...
This works for me:
Create a class which extends UISearchDisplayController:
#interface RVSearchDisplayController : UISearchDisplayController
#end
#implementation RVSearchDisplayController
-(UITableView *) searchResultsTableView {
[self setValue:[NSNumber numberWithInt:UITableViewStyleGrouped]
forKey:#"_searchResultsTableViewStyle"];
return [super searchResultsTableView];
}
#end
Then add a UISearchDisplayController to your table using IB, and change its Custom Class to RVSearchDisplayController in Identity Inspector.
You could try to create a subclass of UISearchDisplayController and make searchResultsTableView searchable
in any .h file add:
#interface YourUISearchDisplayController : UISearchDisplayController {
UITableView * searchResultsTableView;
}
#property (nonatomic) UITableView * searchResultsTableView;
#end;
Then just use YourUISearchDisplayController instead od UISearchDisplayController.
Note: you might have to use (nonatomic, retain), (nonatomic, assign), or (nonatomic, copy). I'm not really sure
This is not possible as the searchResultsTableView property is readonly.
Overriding -searchResultsTableView won't work, because UISearchDisplayController accesses its table view instance variable directly, without calling the method.
The designated initializer for UISearchDisplayController appears to be a private method, -initWithSearchBar:contentsController:searchResultsTableViewStyle:, which sets the _searchResultsTableViewStyle instance variable. This instance variable is used in creating the search results table view. The public initializer calls this method, passing UITableViewStylePlain.
Directly calling the private designated initializer or setting the instance variable would likely get an application rejected from the App Store, so you might instead try overriding the public initializer and calling
[self setValue:[NSNumber numberWithInt:UITableViewStyleGrouped]
forKey:#"searchResultsTableViewStyle"];
Related
I have read about using underscores to fix compiler warnings that say "Local declaration hides instance variable," but I have not been able to implement a fix. The solutions I have read about say to use an underscore in my .h file, and the #synthesize part of in my .m file. However, I do not synthesize my tableView. Please see my header file below:
.h File
#interface ListViewController : GAITrackedViewController <UISearchDisplayDelegate,
UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate> {
IBOutlet UITableView *tableView;
}
.m File
//SYNTHESIZE
#synthesize listItems, filteredListItems, savedSearchTerm, savedScopeButtonIndex,
searchWasActive, mapView, loadingImageView, loadingActivity;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//FIRST WARNING for tableView HERE
if (tableView == self.searchDisplayController.searchResultsTableView){
return [self.filteredListItems count];
}
else{
return [self.listItems count];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//SECOND WARNING for tableView HERE
[tableView setRowHeight: 60.00];
return 1;
}
You have an outlet/property named tableView and your delegate method also contains tableView.
So you need to change either of them. Typically you go to change the argument names of delegate and datasource as
- (NSInteger)tableView:(UITableView *)aTableView
numberOfRowsInSection:(NSInteger)section {
Change :
IBOutlet UITableView *tableView;
To :
IBOutlet UITableView *tableView1;
Make the same required changes in your .m file also. This warning is coming because in below delegate method:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
There is a reference of UITableView with name tableView and you have given the same name. Scope of this variable is function level where as scope of your variable declare in .h is class level.
Dont use same name : IBOutlet UITableView *tableView; use tableview or table_View
I do also spent lot of time on this issue. Finally I could solve this problem.
The thing is we should take care of outlets which are created by us. If you change outlets names then you must connect them properly after change.In my case after lot of struggle I could finish this issue hope it will help others....
For example if You have an outlet/property named tableView and your delegate method also contains tableView.
So you need to change either of them. Typically you go to change the argument names of delegate and datasource as
Change :
IBOutlet UITableView *tableView;
To :
IBOutlet UITableView *tableView1;
For more information visit this link->Local Declaration Hides Instance Variable - tableView Not Synthesized
So I have a Custom UITableViewCell that holds a reference to its containing view controller (the VC that has its table in it).
// MyCell.h
#import <UIKit/UIKit.h>
#import "RootViewController.h"
#interface MyCell : UITableViewCell
#property (nonatomic, strong) IBOutlet RootViewController *rootViewController;
-(IBAction)checkBoxClicked:(UIButton*)sender;
// MyCell.m
#implementation MyCell
#synthesize rootViewController = _rootViewController;
-(IBAction)checkBoxClicked:(UIButton*)sender
{
[self setCheckBoxChecked:!_checkBoxChecked];
[_rootViewController refreshVisibleViewForCellTagged:self.tag];
}
In my cell I have a button that changes a variable and then calls a function in my rootViewController. The method is actually called however when I try to access any object in the RootViewController inside of the refreshVisibleViewForCellTagged method they are are '0x0' / nil;
// RootViewController.h
#interface RootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) IBOutlet UITableView *myTableView;
// RootViewController.m
- (void) refreshVisibleViewForCellTagged:(NSInteger)cellTag
{
UITableView *tableView = self.myTableView; // nil
NSIndexPath *indexPath = [self.myTableView indexPathForSelectedRow]; // nil
MyCell *selectedCell = (MyCell*)[self.myTableView cellForRowAtIndexPath:indexPath]; // nil
if (selectedCell.tag == cellTag) {
NSLog(#"Refresh one way.");
} else {
NSLog(#"Do something else.");
}
}
Can anyone shed some light as to why I cant access any objects/variables in the RootController from within the method 'refreshVisibleViewForCellTagged'?
Please and thank you!
** My big question is Why can't I access any objects when calling a method in a view controller From a different view controller. There is some great programming truth that I am not aware of here, is it a permissions issue? Im not using #class (forward classing) in this instance.
As #trojanfoe said, delegation is a better way to do it.
Instead of #import "RootViewController.h", it is better to adop delegation. Because UITableViewCell is a child and RootViewController is the parent view. You don't want the child to talk directly with the parent.
To adopt delegation:
in MyCell.h file
remove #import "RootViewController.h".
revise MyCell.h as follows:
#protocol MyCellDelegate; // if you need to have forward declaration
#interface MyCell : UITableViewCell
// #property (nonatomic, strong) IBOutlet RootViewController *rootViewController;
#property (nonatomic) id <MyCellDelegate> delegate;
#end
#protocol MyCellDelegate <NSObject>
- (void)refreshVisibleViewForCellTagged:(NSInteger)cellTag;
#end
in MyCell.m.
#synthesize delegate;
-(IBAction)checkBoxClicked:(UIButton*)sender {
[self setCheckBoxChecked:!_checkBoxChecked];
//[_rootViewController refreshVisibleViewForCellTagged:self.tag];
[self.delegate refreshVisibleViewForCellTagged:self.tag];
}
in RootViewController.h adopt the delegation of MyCell
#import "MyCell.h"
#interface RootViewController : UIViewController <MyCellDelegate>
in RootViewController.m.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = // your implementation
//assuming all your cells are of MyCell kind
// set RootViewController as the delegate of each cell
((MyCell *)cell).delegate = self;
return cell;
}
implement the delegate method in RootViewController.m.
- (void)refreshVisibleViewForCellTagged:(NSInteger)cellTag {
// whatever you have
}
P.S. The above codes are for illustration. I didn't run them. If some part doesn't work, let me know, and I'll revise it.
The reason those objects in RootViewController are nil in the way you call, is because you are not accessing the same instance of RootViewController. It is a different (new) instance and hence all objects are nil.
Ignore the fact that view controllers are even involved. What you have are OBJECTS, connected together in a certain pattern. Accessing data in another view controller is no different from accessing data in any other object. There's no "magic" with view controllers, other than they have a few standardized connections to other objects.
IMHO, this is a poor design. For starters, your cell shouldn't need a reference to the view controller that the table it's in is in (read that twice, it barely makes sense just because the very idea of it is confusing). You have a strong reference to this view controller. So what happens when the OS tries to deallocate your view controller? It will never be able to, because the table view cell as a strong reference to it, keeping its retain count at 1. The same situation holds true for the cell. You risk running into a retain cycle here. Generally, child views should have weak references to their parents.
But this isn't even really a true parents/child relationship. I would suggest instead an approach like this, which all occurs in your view controller that contains the table view:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Assuming you set a reuse identifier "cellId" in the nib for your table view cell...
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:#"cellId"];
if (!cell) {
// If you didn't get a valid cell reference back, unload a cell from the nib
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:#"MyCell" owner:nil options:nil];
for (id obj in nibArray) {
if ([obj isMemberOfClass:[MyCell class]]) {
// Assign cell to obj, and add a target action for the checkmark
cell = (MyCell *)obj;
[cell.checkMarkButton addTarget:self action:#selector(checkPressed:) forControlEvents:whateverEventYouWant];
break;
}
}
}
// Set the tag of the cell here, since we may get a different cell back from the reuse queue
cell.checkMarkButton.tag = indexPath.row;
return cell;
}
Now set up the method for the clicking of the checkmark button
- (void)checkPressed:(id)sender {
UIButton *checkmark = (UIButton *)sender;
// This will give you the row of the checked button
int checkedCellRow = checkmark.tag;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:checkedCellRow inSection:0];
// Now you can grab a reference to that cell if you need to
MyCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
}
This way, you keep all of the controller-related stuff in your controller class (i.e. how to handle the checkmark button being pressed), and you don't need to deal with this whackiness of referencing the view controller of your cell's table.
EDIT: I guess I should also help answer your questions...First of all, if you're saying that in your refreshVisibleViewForCell method, you're getting a nil value for self.myTableView, are you sure it is hooked up properly in IB? Even if it's hooked up, click the little x to unhook it and hook it up again to be sure. Also make sure you've #synthesized your myTableView property. Without seeing more code, an IB issue is my best guess as to why you're getting a nil value for tableView. A nil value here will result in a nil indexPath and selectedCell, also. As for your big question, you can access properties of objects within your view controller. Those properties can, of course, be objects. So in your example, if you have a tag property on selectedCell, you can access it from anywhere that you have a valid reference to selectedCell. If selectedCell is nil, the property will be nil. #class is better suited for header files. For instance, if you wanted to make your custom cell a property of your view controller, you might say:
#import <UIKit/UIKit.h>
#class MyCell;
#interface RootViewController : UIViewController
#property (nonatomic, strong) MyCell *cell;
#end
Then, in your implementation file, you would actually import MyCell.h. Giving the #class forward declaration just keeps you from having to import all of the details about the MyCell class in your header file. The header doesn't need to know about all of the properties and methods of MyCell, just that you intend on using it in the implementation file. So you #class in the header, #import in the implementation.
in RootViewController.h:
#interface RootViewController : UITableViewController <UITableViewDelegate>
in RootViewController.m:
- (void) refreshVisibleViewForCellTagged:(NSInteger)cellTag {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
MyCell *selectedCell = (MyCell*)[self.myTableView cellForRowAtIndexPath:indexPath]; // nil
etc...
I'm not seeing declarations of myTableView in your RootViewController. But if your RootViewController implements UITableViewController, you can use self.tableView to access the tableview. You don't need to keep a reference to it by yourself.
#RachelD, if your RootView is more complicated than just a UITableViewController consider using a separate class, such as RootTableViewController. Then in your RootView xib, create IBOutlet for RootTableViewController to reference it. Like this:
// RootTableViewController definition
#interface RootTableViewController : UITableViewController
{
}
// RootViewController definition
#interface RootViewController : UIViewController
{
RootTableViewController *table_c;
}
#property (nonatomic, retain) IBOutlet RootTableViewController *table_c;
Note that you need to drag an "Object" into the "Objects" section (for RootViewController) in the interface builder, and type RootTableViewController in the Custom Class section for this object. Right click this object, make sure its IBOutlet, view, 2 delegates are correctly set.
The reason why your myTableView is nil is because it's not properly initialized. I mean, if you don't use UITableViewController you are responsible for assigning it manually via interface builder or something.
I am just curious. In IB, we can put a tableviewcontroller. However, as far as I know, we always subclass that tableview controller right? That way we can implement delegate, etc.
However, it seems that for some "default" behavior, IPhone intended tableviewcontroller to be used as is. Otherwise, why would IB let us put tableViewController like that?
Are there any sample code where people use tableViewController without subclassing?
Where does they implement things like what cells to draw, etc. then?
I guess the right answer of the question is that it's simply ridiculous to use a UITableViewController without sub classing. No body is doing it. Please correct me if I am wrong. I am just curious.
Whether you use a subclass of UITableViewController or UIViewController you need to set the data your table is going to display, otherwise, what's the point of a blank table? To achieve that you have to subclass and implement some methods. It's also a good idea to keep the delegate and the datasource in the same controller, unless the complexity really asks for different classes.
That being said, I always create my own table controllers as a subclass of UIViewController and implement the table controllers methods myself, because it gives you more flexibility. Matt Gallagher has several posts on how and why. See UITableView construction, drawing and management (revisited).
If you want to give it a try, create a subclass of UIViewController with a XIB and add the following sample code:
// interface
#import <UIKit/UIKit.h>
#interface SettingsVC : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *array;
#end
// implementation
#synthesize tableView = _tableView;
#synthesize array = _array;
# pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.array count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int row = [indexPath row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [self.array objectAtIndex:row];
return cell;
}
Then add a UITableView object to the XIB, link the tableView of the controller to the UITableView object, and link the delegate and datasource of the UITableView to the controller.
No, this is not necessary to inherit your class with tableViewController. You can use table view by simply
putting TableViewController in xib.
and setting its delegate and datasourse to file's owner you can draw the table cells.
I don't think you can use a UITableViewController as is, it's like using a UIViewController without subclassing it : you can't set any inner mechanics.
But you can have a UITableView without using a UITableViewController.
Sure you can use UITableViewController without subclassing it.
Samplecode is very easy and straight forward.
For example like this:
- (IBAction)selectSomeOption:(id)sender {
UITableViewController *tableViewController = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
tableViewController.tableView.dataSource = self;
tableViewController.tableView.delegate = self;
tableViewController.title = "Select some option";
[self.navigationController pushViewController:tableViewController animated:YES];
}
and the UITableViewDatasource and Delegate methods go into the same class.
Sure, if you like pain you could create a UIViewController in code and add a tableView on your own.
Or create a subclass for such an easy task.
The use of a non subclassed UITableViewController is sometimes convenient.
My iphone program has a Xib view with a tableview dropped in. I've subclassed UITableViewController and am trying to make the UITableView in the xib send it messages. The program crashes when I touch a tableview row.
It properly calls:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{}
and the cell.textLabel.text is assigned properly.
Interface snippet:
#interface PlayersDrawsViewController : UIViewController {
UITableView *uitableView;
PlayersToDrawTableViewController *pvc;
}
#property (nonatomic, retain) IBOutlet UITableView *uitableView;
#property (nonatomic, retain) IBOutlet PlayersToDrawTableViewController *pvc;
Implementation snippet:
- (void)viewDidLoad
{
// Setup TableView
if (pvc == nil) {
pvc = [[PlayersToDrawTableViewController alloc]
initWithNibName:#"PlayersToDrawTableViewController" bundle:nil];
/* works great, loads rows */
self.uitableView.dataSource = pvc.tableView.dataSource;
/* EXC_BAD_ACCESS when didSelectRowAtIndexPath is called */
//self.tableView.delegate = pvc;
}
}
My UITableViewController Subclass:
#interface PlayersToDrawTableViewController : UITableViewController
<UITableViewDelegate>
{
}
#end
How can I get the delegate hooked up so it doesn't crash sending messages?
I've read these threads and either I'm dense or they don't answer my question:
UITableView issue when using separate delegate/dataSource
UITableView superClass for delegate?
Getting “EXC_BAD_ACCESS” when accessing instance variable from within UITableView delegate method
didSelectRowAtIndexPath generates EXC_BAD_ACCESS while willSelectRowAtIndexPath works fine UITableView
If this line is crashing with EXC..:
self.tableView.delegate = pvc;
...did you hook up the tableView reference somewhere? In your code snippet "no" - but maybe you did in the NIB?
When creating a custom UITableView cell I manually define a delegate variable in the #interface of a UITableViewCell class (each cell must communicate with parent class so the connection betweet two classes is needed). Then when a cell is attached to a UITableView, I just set that delegate variable.
#interface MyCellClass : UITableViewCell {
MyParentController *delegat;
}
#property (nonatomic, retain) MyParentController *delegat;
Is there a better way of doing it?
That could be ok but be sure you don't make retain cycles. (A retains B, B retains A, none of them get never released)
If you are just using only a functionality of MyParentController then, it is a good idea to make a protocol and set a delegate as an object that adopts (implements) that #protocol, It is not mandatory but it is good practice and better design this way.
You could create your protocol like:
//MyProtocol.h
#protocol MyProtocol <NSObject>
#required
- (void) requiredMethod:(NSString *)param;
#optional
- (void) optionalMethod:(NSString *)param;
#end
And Make your class:
#import "MyProtocol.h"
#interface MyCellClass : UITableViewCell {
id<MyProtocol> delegate;
}
#property (nonatomic, assign) id<MyProtocol> delegate; //see I changed it to assign?
Also, when you have delegates you should avoid making them retain or you will have retain cycles and hence, memory leaks.
That's the way I usually do it. Just create the cell and set its delegate before returning it in
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath