Is it possible to create multiple columns in UITableView? - iphone

I want to add more columns in my iPhone/iPad application. Is it possible to add more columns in one UITableView? Can you please suggest any sample code/block/project that using multiple columns in one UITableView? Please help me. Thanks in advance.

No it is not possible, in fact UITableView is badly named a represents a List more than a Table.
If you want to have multiple column, one method is to create specific cells, with multiple label, and pack your data by row then column.

short answer is no, but you always can create custom cell what will look like multiple columns

You can use my library, UIGridView.
It is created with UITableView, in which UITableViewCell contains many cells inside.
Here is how it looks like:

No Yuvaraj.M we can't create. but you do something like multicolumn by adding component like label or image or button what u want or else using custom cell.

I've done a grid by using a table view where I have basically faked it by adding subviews to a cell. So if you for example create a cell, add three subviews to it, you can then get the items you need by doing something like this when it asks you for a cell for a specific row:
// get the items for the row (a row is one cell)
NSArray *rowItems = nil;
int startIndex = indexPath.row * NumOfItemViewsPerRow;
if (startIndex + NumOfItemViewsPerRow < [items count]) {
rowItems = [items subarrayWithRange:NSMakeRange(startIndex, NumOfItemViewsPerRow)];
} else {
rowItems = [items subarrayWithRange:NSMakeRange(startIndex, [items count] - startIndex)];
}
Then just after that you can loop the subviews of your row something like this:
[cell.itemViews enumerateObjectsUsingBlock:^(MyItemView *itemView, NSUInteger idx, BOOL *stop) {
NSDictionary *item = [rowItems objectAtIndex:idx];
itemView.titleLabel.text = [item valueForKey:#"title"];
};
It is a bit fiddly, but the upside is that you get row unloading for free from the table view, so you don't have to mess with your own custom grid views or anything like that.
Hope that helps.

Related

How to implement table with row and column

How to implement a table like in the image? Table with Row and column? Can any tell me the refrence for iphone
The columns are just an illusion.
This is done by subclassing UITableViewCell and designing the cell to have a UIImageView and three UILabels.
Assign the imageView and labels to properties of your subclass and you can configure it this way...
Object *object = [self.datasource objectAtIndexPath:indexPath];
cell.imageView.image = object.image;
cell.subCategoryLabel.text = object.subcategory;
cell.dateLabel.text = object.dateString;
cell.scoreLabel.text = [NSString stringWithFormat:#"%i", object.score];
or something like this.
Then the layout of the labels gives the illusion of having columns.
You need to create custom cell exact according to your requirement. Add data dynamically by adding row and column. Read this http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/tableview_iphone/TableViewCells/TableViewCells.html documentation before implementing custom cell.

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)

Decrease indexPath by one

I'm filling a TableView with CoreData.
Until now I was doing something like this:
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
...to retrieve the object to fill the row.
Everything was working fine until I realized I have to manage the first row of the table as an exception because the first line will contain other content, not provided by CoreData.
Now my issue is how can I manipulate the indexPath to shift everything by one. I would like to do something like this:
// I know this is not going to work, just to give you an idea...
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath-1];
but I cannot find the right syntax to manipulate the indexPath. Can anyone help me?
Thx for your time!
In case we are talking about iOS UITableView index path there's much easier way:
NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:oldIndexPath.row+1 inSection:oldIndexPath.section];
Cheers... :)
If you're talking about a standard iOS UITableView, then your index path is an instance of NSIndexPath, and will have two entries: a section index and a row index. If I understand you right, you want to decrement the row index by 1 every time you go to fill a table view cell. (I'm assuming you only have one section, or don't care about the section index - if this is wrong, please edit your question.)
Basically what you need to do is construct a new NSIndexPath instance with your adjusted indices, then use that to query your fetched results controller. Something like this would work (untested):
NSUInteger indexes[2];
[indexPath getIndexes:indexes];
indexes[1]--;
NSIndexPath * adjustedIndexPath = [[NSIndexPath alloc] initWithIndexes:indexes
length:2];
NSManagedObject * managedObject = [self.fetchedResultsController
objectAtIndexPath:adjustedIndexPath];
This basically does the following:
Pulls the existing indexes into a C array of NSUIntegers
Decrements the last index (at position 1 - the row index) by 1
Creates a new NSIndexPath with the adjusted indexes from the C array
Fetches the managed object using the new index path
Note again that this doesn't touch the section index at all, and so will adjust every cell in your table, regardless of whether it's in your first section. If that's not what you want, either wrap the adjustment in a conditional (e.g. if([indexPath indexAtPosition:0] == 0)) or add your own custom logic.

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.