Referencing UISwitches within UITableCells - iphone

I have a table view which I'm using for some settings in my app. The tables cells are all default (no customisation at all), and simply contain some text for their label and a UISwitch for the accessory view.
My problem is that I need a reference to the switch so that I know when it has been switched on and off.
Currently I am setting the 'tag' property of the switch to be that of the cell's index within the table (grabbed from [indexPath row] in tableView:cellForRowAtIndexpath:).
This is fine when you only have one Section in your table, but I am now adding a new section. The problem is that they are both 0 based indexed so the switches in each section will end up reusing the tags - which isn't good.
Any suggestions on a better way to achieve this?
Thanks.

If you know roughly how many sections and rows you will have, like oh, say, not more than 1 million rows per section, just hash the section and row like this:
const int oneMillion = 1000000;
int tag = (section * oneMillion) + row;
slider.tag = tag;
Then, to figure out the section and row, reverse the logic:
int tag = slider.tag;
int row = tag % oneMillion;
int section = tag / oneMillion;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow: row inSection: section];
Now get the slider that is in the cell in that section,row of the table
UITableViewCell *sliderCell = [tableView cellForRowAtIndexPath: indexPath];
UISlider *slider = [[sliderCell.contentView subviews] objectAtIndex: 0];
This assumes the slider is always the only view in the contents of the cell.
This method is a bit longer than some of the other suggestions above, but it keeps you from having to cache references off to the side.

For each cell, set a delegate link back to the table view controller, and also some kind of row reference ID - then wire the switch to a cell IBAction method, that calls back to the delegate with the reference ID for that cell.

What you can do is either have an Array of arrays or a dictionary, key it by the section number (or in case of the array they will be in order of the section numbers), now to retreive a switch all you do assuming you know the section and the row number
UISwitch *switch=[[switchArray objectAtIndex:section] objectAtIndex:row];
or if you have a dictionary
UISwitch *switch=[[switchDictionary objectForKey:section] objectAtIndex:row];

Related

Iterate all cells in s UITableView

I want to iterate all uitablewview cells and display the text of a uitextview contained in each cell.
My table can have many rows and to reach all you must scroll. I made an implementation, but it displays the text only for current visible cells in scroll, for the others gives me null.
for (int i = 0; i < [propertiesTableView numberOfRowsInSection:0]; i++) {
UITableViewCell* cell = [propertiesTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
UITextView* tx = (UITextView*)[cell viewWithTag:2];
NSString* temp = tx.text;
NSLog(#"%#", temp);
}
How to fix this?
This happens because only the visible cells are instantiated (remember the dequeueReusableCellWithIdentifier: function?). You should extract the needed information from the table data source.
Yes this behavior is expected, because of performance considerations the table view does not holds all cells initialized all the time. Your solution is just to update your data source - if it's an array for example, iterate though it and change the values accordingly - this is the power of MVC (fast UI, separate model)

Selecting multiple rows of a UITableView

This page
http://networkpx.blogspot.com/2009/07/multiple-row-selection-with-uitableview.html
mentions a way to implement table views that can allow multiple selections of rows.
At the time of this article, it seems that it was not a blessed way of doing this.
Now, apparently, Apple is allowing this kind of tableViews.
The article mentions this
NSArray* selectedRows = [tableView indexPathsForSelectedRows];
as a way of getting a list of all rows selected but this is not a legal functionality of the SDK.
The big question is: how do I get a list of all rows selected, so I can perform an action with them?
thanks
EDIT
To answer some questions... this is the code I am using to discover if a row is selected, but this is giving me zero entries.
NSMutableArray *selectedRows = [[NSMutableArray alloc] init];
for (int i=0; i<[list count]; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
UITableViewCell *aCell = (UITableViewCell*) [myTable cellForRowAtIndexPath:indexPath];
if (aCell.accessoryType == UITableViewCellAccessoryCheckmark) {
[selectedRows addObject:indexPath];
}
}
// selectedRows has always 0 entries... all cells give me their type as UITableViewCellAccessoryNone even those with checkmark
Apple will reject your app for for iOS 4 and below.
We found the following non-public API/s in your app:
indexPathsForSelectedRows
Create a NSMutableArray.
Whenever a table cell is selected insert the current indexpath in the array. whenever he deselects the cell remove it from the array. Final array will have everything you selected.
MultipleCheck in Table – UITableView Example with Demo
http://sugartin.info/2011/08/19/multiplecheck-in-table-uitableview/
Are you looking to have the user select multiple rows at the same time? If not you could create an array that holds each row that is selected as the user selects them.
Also for the check mark you could just subclass UITableViewCell.
How to subClass UITableViewCell and use it to not clear UILabel background color on UITabeViewCell selected?

Check all items in iPhone UITableView

I have a UITableView where every cell either gets/loses a checkbox or goes to another table view when clicked. For every table, I want to add a check all button that checks off every cell in that table and all the ones inside it. How do I allow one UITableViewCell to toggle the checkbox of every one in it's TableView?
EDIT: Removing the last index in the index path, and replacing it by the new row number, I'm able to go through the entire table and check it off, like this:
for(int i = 0; i < [tableView numberOfRowsInSection:0]; i++){
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:[[indexPath indexPathByRemovingLastIndex]
indexPathByAddingIndex: i]];
newCell.accessoryType = UITableViewCellAccessoryNone;
}
Oddly, it skips over every tenth cell or so - and it's not even consistent. For a list of years, sometimes it doesn't check off 2003 and 1993, sometimes 2003 and 1991, and and so on. It's always around every tenth cell or so, but I can't find a pattern.
When you click the cell didSelectRowAtIndexPath will be called, at that point all you gotta do is use tableView cellForRowAtIndexPath:indexPath method in order to get back all your cells one by one and set their accessory type to checkmark...hope this helps
EDIT: Another way to do it is, if you have maybe some sort of array (hard to tell you what to do exactly without looking at your code), but if you have some array that holds values as to which cells need have check marks on them, then you can use in cellForRowAtIndexPath to assign the checkmark accessory, so when your cell is selected, you can set all the values in the array to what you need them to be and just call UITableViews reloadData...hope that made sence :), heres a little snipet of code to try and make it more clear
lets assume you have 1 section and x amount of rows
NSMutableArray shouldHaveCheckmark; //this array will be of size x
//(one for each row) and hold NSNUmbers 0 means not checked 1 means checked you initialize
//this somewhere (viewDidLoad maybe) and should be declared in your .h file
//this is cellForRowAtIndex path
-(UITableViewCell)cellForRowAtIndexPath:(NSIndexPath*)path
{
UITableViewCell *cell=...
if([[shouldHaveCheckmark objectAtIndex:path.row] boolValue] )
//assign checkmark accesory
//other code
return cell;
}
So you can see in didSelectRowAtIndexPath you can just flip the numbers in the array and call reloadData on the tableView...that approach will work as well

How can a UITableViewCell know of its own indexPath?

The standard Grouped UITableView style allows UITableViewCells to be drawn with rounded corners at the top and bottom of each section. How is this accomplished? How does the cell know its own location within its section, and how does it know when to change its rounded edges?
I want to make my own rounded cells, and I have images to use, but don't know when to show which image
Note: I already know how the UITableView works, and I know how to use it. I just thought that since a UITableView is able to automatically draw rounded corners at the correct places, I should be able to as well, without needing to add anything to my data source or delegate.
NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
int rows = [(UITableView *)self.superview numberOfRowsInSection:indexPath.section];
if (indexPath.row == 0 && rows == 1) {
// the one and only cell in the section
}
else if (indexPath.row == 0) {
//top
}
else if (indexPath.row != rows - 1) {
//middle
}
else {
//bottom
}
It's very simple. suppose cell is the object, whose position is to be found out.
UITableView* table = (UITableView *)[cell superview];
NSIndexPath* pathOfTheCell = [table indexPathForCell:cell];
NSInteger sectionOfTheCell = [pathOfTheCell section];
NSInteger rowOfTheCell = [pathOfTheCell row];
There is sectionLocation method of UITableViewCell that returns integer telling you what you need:
1 - middle cell
2 - top cell
3 - bottom cell
4 - single cell
I had no issues using this in several production apps since 2010.
UPDATE: one of our binaries was automatically rejected recently (end of 2018) because we were using 'sectionLocation' property, so it's not a good option anymore.
Add something like this into your header files and you can use it:
typedef NS_ENUM(NSInteger, MMMTableViewCellLocation) {
MMMTableViewCellLocationUndefined = 0,
MMMTableViewCellLocationMiddle = 1,
MMMTableViewCellLocationTop = 2,
MMMTableViewCellLocationBottom = 3,
MMMTableViewCellLocationSingle = 4
};
#interface UITableViewCell ()
/** Undocumented method of UITableViewCell which allows to know where within section the cell is located,
* so the cell can draw its borders properly. */
- (MMMTableViewCellLocation)sectionLocation;
/** Override this one to know when the value of sectionLocation changes. */
- (void)setSectionLocation:(MMMTableViewCellLocation)sectionLocation animated:(BOOL)animated;
#end
You can use
- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell
for this issue. In my example I am using this to scroll the cell (with custom content) to the top of the view.
If you need more robust and general stuff, take a look at http://cocoawithlove.com/2009/04/easy-custom-uitableview-drawing.html - Matt Gallagher shows what you need, pretty effectively. He basically recreates UITableViewController from UIViewController, while adding ability to use your own custom graphics. I'm just working on applying this to one my projects, so far it looks it would do the job.
Unfortunately, I have found no solution to this problem, and have resorted to subclassing UITableViewController and UITableViewCell into a generic solution that I can extend as necessary.
You don't do this in cell. Rounded corners are drawn in [tableView viewForHeaderInSection] and viewForFooterInSection.
The way I do it is to use Plain tableview style, then use these two views for roundness and cells are normal, no rounds.
Without getting into who draws what, you can know which cell is the last cell in its section inside of cellForRowAtIndexPath very easily.
You're passed in the indexPath of the cell you need to provide, right? You're also passed the tableView.
call [tableView numberofRowsInSection:indexPath.section] and if it's == ([indexPath.row]-1) you know you're being asked to supply the last cell in that section.
At the time that cellForRowAtIndexPath is being called, the cell is guaranteed to be at the indexPath passed in.
To expand upon Darren's answer (which I found most useful, thanks Darren!), what you can do is to iterate through all of the superviews' until you find the parent UITableView. This should be future proof since you do not rely on a fixed hierarchy of views.
I use a recursive method that will return the UITableView if it finds one or return nil if there is none.
- (UITableView *)parentTableViewOf:(UIView *)view {
Class class = [view.superview class];
NSLog(#"Class : %#", NSStringFromClass(class));
if([view.superview isKindOfClass:[UITableView class]]) {
return (UITableView *)view.superview;
} else {
return [self parentTableViewOf:view.superview];
}
return nil;
}
So far I've used this one and it seems to work without hiccups. Hope it helps! :)
The cells dont know where they go...The table view has cells, You are the one telling the table view WHAT goes in the cell. You do this in the DataSource where you implement cellForRowAtIndexPath...The way this works :
An index path has a row and a section
For a grouped table view
A section pertains to a group, and a row pertains to 1 entry in that section,
the way UITableView knows how many rows are in a section and how many sections there are is the DataSources methods numberOfSectionInTableView and the method numberOfRowsInSection, this will make the right calls to cellForRowAtIndexPath, it is up to you to recognize which section and row is being queried and you need to build your cell according to these specifications.
A good way to do this i s you can have a Dictionary with keys of section names and values of NSArray with the values that go in that section.
So you implementation for numberOfSectionsInRows would look like
return [[dictionary allKeys] count]
And the implmentation of numberOfRowsInSection would look like
NSString* key=[[dictionary allKeys] objectAtIndex:sectionNumber]
return [[dictionary objectForKey:key] count]
You can always refer to the UITableView programming guide at http://developer.apple.com/iphone/library/documentation/UserExperience/Conceptual/TableView_iPhone/Introduction/Introduction.html
Hope that helps
Simply add a property to your custom UITableViewCell (depending on implementation) class that contains an int, NSNumber, or an NSIndexPath specifying which one it is. In you're using a data structure instead, then put it in you element in that data structure. Then you simply set the property when you create the data structure, something like elt.id=i, and then you access it in the cellForRowAtIndexPath, something like if (elt.id == 0 || elt.id == n-1) where n is the number of rows in your section.
I might have totally missed your question, but if I did, just comment and I'll post again.

iPhone SDK: Inserting and updating a UITableView with a new row

I have a tableView that needs to be updated after information has been inserted from another view. If I perform a
[self.tableView reloadData];
The very next time I insert more information in another view and try to reload the table, all the currently visible rows are duplicated.
In other words, when I start up the app I have:
tableView:
Row 1
Row 2
Then I submit some information that will also show up in the table and suddenly I have:
tableView
Row 1
Row 2
Row 3 <- info I just added
Row 1
Row 2
My numberOfRowsInSection implementation looks like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [ItemsController sharedItemsController].count;
}
My cellForRowAtIndexPath implementation looks like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ItemsController* controller = [ItemsController sharedItemsController];
NSMutableArray* recentItems = controller.listOfRecentItems;
CustomCell *cell = nil;
NSUInteger row = [indexPath row];
if( row < recentItems.count )
{
Items* item = [recentItems objectAtIndex:row];
if( recentCellData == nil )
recentCellData = [[NSMutableDictionary alloc] initWithCapacity:[indexPath length]];
if( [recentCellData count] > 0 )
cell = [recentCellData objectForKey:[NSString stringWithFormat:#"%d", row]];
if (cell == nil) {
UIViewController * view1 = [[UIViewController alloc] initWithNibName:#"CustomCell" bundle:nil];
cell = (CustomCell*)[view1 view];
[recentCellData setObject:cell forKey:[NSString stringWithFormat:#"%d",row]];
}
// do some other stuff here
}
// Set up the cell
return cell;
}
What's the best way to update the table and avoid duplicating the currently visible rows.
Thank in advance for all the help!
The error isn't in how you're reloading the table, it's in how you're providing data to it. Set a breakpoint in the data source methods and the method that adds new rows to see where you're going wrong.
You'll only end up with five items if tableView:numberOfRowsinSection: returns 5. Thats the simple answer to your question, but I see other problems here. I'm wondering why you have this test: row < recentItems.count. Is that array the same thing as [ItemsController sharedItemsController].count? You really need to be using the same array for both methods.
(Also, it's not a syntax error, but you shouldn't use the property syntax for things that aren't declared as properties. You should write [recentItems count] instead.)
I'm also confused by the code you use to set up the cell. Cells are meant to be reusable. That is, you create one cell, then reconfigure it every time in your implementation of tableView:cellForRowAtIndexPath:. Your code creates a cell for each item in your list. This is very memory-inefficient, and will likely crash your program due to insufficient memory on the iPhone if you keep lots of cells in memory like this.
The recommended approach is to call dequeueReusableCellWithIdentifier:. If that returns nil, then you set up a cell using the initWithFrame:reuseIdentifier: initializer. The table view is very smart, and will only ask you to redraw the cell when it needs you to.
Your recentCellData dictionary looks really shaky to me, too. What if you insert an item after the item with key #"2"? All the items with key #"3" onward will need to be shifted one element to the right to work the way you expect. That's a ton of bookkeeping that seems rather unnecessary to me. If you really needed something like this -- and to be clear, I don't think you do -- why wouldn't you use an NSMutableArray, which is much easier to use?
I added a bit more info above.