Reputation: 4489
I am using following method in my application:
- (UITableViewCell *)tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath
In this method by using indexPath.row
I can get the row number of each row.
But I want to actually access the cell at that row and do some formatting on that cell only.
Please guide me.
Upvotes: 3
Views: 6562
Reputation: 7588
While the other answers will work fine, but it will just change the cell that the user tapped on. For my case I wanted to change the other cells as well. After searching around, I tried:
[[tableView cellForRowAtIndexPath:5 setAccessoryType:UITableViewCellAccessoryNone];
This does NOT work, because IndexPath is not an integer. (indexpath.row is, however). So, upon looking up the doc, I found out that we can use NSIndexPath to encode a row into NSIndexPath value. Here is the working code:
[[tableView cellForRowAtIndexPath: [NSIndexPath indexPathForRow:5 inSection:0]] setAccessoryType:UITableViewCellAccessoryNone];
This way, you can access the cell ANYWHERE, AT ANY ROW/SECTION, provided you have the tableview object.
Hope this helps someone.
Upvotes: 6
Reputation: 7494
Maybe there is a misunderstanding. The method you are quoting is supposed to tell the tableView which row to display at that indexPath. So, whenever the tableView asks for this method, it does so because there is no row at this indexPath yet.
The template code will generate a new cell or dequeue one:
- (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] autorelease];
}
You can then access cell
to configure the content of each cell or add content to the contentView.
If you manipulate the formatting of a cell on a per row basis (e.g. the color of the cell.textLabel) you should do this in the following delegate method:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
Upvotes: 2
Reputation: 170859
You can access a visible cell using UITableView -cellForRowAtIndexPath
method. From UITableView reference:
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
Return Value
An object representing a cell of the table or nil if the cell is not visible or indexPath is out of range.
However (IMO) cellForRowAtIndexPath
is the best place for a cell setup.
Upvotes: 1