I had a problem with table view didSelect method and prepareForSegue. I used SWRevealController in my app. While selecting cell it reveals the view. Sometimes it not worked properly. It takes two taps to reveal the view. A few months back I used old reveal view frame which contains perform block action. Its worked perfectly.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
for (int i=0; i<6; i++)
{
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
if (i == indexPath.row)
{
cell.contentView.backgroundColor = [UIColor colorWithRed:KColorRedSelected green:KColorGreenSelected blue:KColorBlueSelected alpha:1];
}
else
{
cell.contentView.backgroundColor = [UIColor colorWithRed:KColorRed green:KColorGreen blue:KColorBlue alpha:1];
}
}
}
Add this code inside of didSelectRowAtIndexPath and didDeselectRowAtIndexPath functions
dispatch_async(dispatch_get_main_queue(), ^{
//Write code what you need
});
That works for me.
The problem is with this line
[self tableView:tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
You are calling the delegate method, which dequeues a reusable cell (I assume, since it's standard behavior). You do not want to dequeue a reusable cell, you want to do something with a cell that is currently displayed at indexPath. To do that use method from UITableView
[tableView cellForRowAtIndexPath:indexPath];
The full code
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// grab the selected cell and give it selected color
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithRed:KColorRedSelected green:KColorGreenSelected blue:KColorBlueSelected alpha:1];
}
- (void)tableView:(UITableView*)tableView didDeselectRowAtIndexPath:(NSIndexPath*)indexPath
{
// grab the deselected cell (if it's still visible) and give it deselected color
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithRed:KColorRed green:KColorGreen blue:KColorBlue alpha:1];
}
You will also need to set appropriate color in UITableViewDelegate method cellForRowAtIndexPath, since the color you once set will stay in the cell when it's reused.
This s completely wrong method to get clicked cell
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
And don't use for loop as well. instead of this you should use
UITableViewCell *cell = [tableView cellForIndexPath:indexPath];
to get correct cell.
Related
I have a UITableView as a subview of a View. In the ViewController when the table is being populated I'm highlighting one of the rows and keeping a record of the indexPath for that row. I'm doing this in the cellforRowAtIndexPath method.
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
favouriteCellView *cell = [tableView dequeueReusableCellWithIdentifier:#"reuseID"];
QBCOCustomObject *favouriteObject = [_favouriteResults objectAtIndex:indexPath.row];
if (favouriteObject.userID == self.user.ID) {
UIView *bgColor = [[UIView alloc] init];
bgColor.backgroundColor = [UIColor colorWithRed:173.0f/255.0f green:146.0f/255.0f blue:237.0f/255.0f alpha:.5];
self.highlightedRowIndex = indexPath;
[cell setSelectedBackgroundView:bgColor];
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
}
return cell;
}
Then in the viewDidAppear Method I want the table to scroll to the highlighted cell.
-(void)viewDidAppear:(BOOL)animated{
[self.tableView scrollToRowAtIndexPath:self.highlightedRowIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
However I've double checked that the method is being hit with a breakpoint, but unfortunately the highlighted row is not being scrolled to the top of the table as I'd expected. AM I misunderstanding the scrollToRowAtIndexPath method? Or have I left something out of the above code.
If the row is not on screen, it will not yet be loaded by the table view. This means your cellForRowAtIndexPath for that cell will not yet be called. You'll want to choose this index in a way that does not depend on the view loading. Try this before you call scrollToRowAtIndexPath:
NSInteger row = 0;
for (QBCOCustomObject *object in _favouriteResults) {
if (object.userID == self.user.ID) break;
row++;
}
self.highlightedRowIndex = [NSIndexPath indexPathForRow:row inSection:0];
I have a custom UITableViewCell, and when it's selected, it expands and adds a UILabel to the selected cells UIView that I added in the storyBoard.
When I run the app and select a cell, the label gets added to myView as expected. The problem is, when I scroll down, the label is also shown at another cell.
Apparently the reason its behaving like so, is because I'm reusing the cell and I don't clean them as Emilie stated. I'm trying to call the method of prepareForReuse and 'cleaning' the cell, but I'm having trouble doing that. Here is my code:
- (void)prepareForReuse {
NSArray *viewsToRemove = [self.view subviews];
for (UILablel *v in viewsToRemove) {
[v removeFromSuperview];
}
Doing that, cleans even the selected cells label.
- (void)viewDidLoad {
self.sortedDictionary = [[NSArray alloc] initWithObjects:#"Californa", #"Alabama", #"Chicago", #"Texas", #"Colorado", #"New York", #"Philly", #"Utah", #"Nevadah", #"Oregon", #"Pensilvainia", #"South Dekoda", #"North Dekoda", #"Iowa", #"Misouri", #"New Mexico", #"Arizona", #"etc", nil];
self.rowSelection = -1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CategorieCell *customCell = [tableView dequeueReusableCellWithIdentifier:#"cellID" forIndexPath:indexPath];
customCell.title.text = [self.sortedDictionary objectAtIndex:indexPath.row];
return customCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
CategorieCell *customCell = (CategorieCell *)[tableView cellForRowAtIndexPath:indexPath];
if (self.info) {
[self.info removeFromSuperview];
}
self.info = [[UILabel alloc] init];
[self.info setText:#"Hello"];
[self.info setBackgroundColor:[UIColor brownColor]];
CGRect labelFrame = CGRectMake(0, 0, 50, 100);
[self.info setFrame:labelFrame];
[customCell.infoView addSubview:self.info];
NSLog(#"%ld", (long)indexPath.row);
self.rowSelection = [indexPath row];
[tableView beginUpdates];
[tableView endUpdates];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([indexPath row] == self.rowSelection) {
return 159;
}
return 59;
}
The answer is quite simple : you reuse your cell like you should, but never clean them
Reusing your UITableViewCell means that the cell you clicked on previously will be reused when it will go off-screen.
When clicked, you add a view to your UITableViewCell. When reused, the view is still there because you never remove it.
You have two choices : One, you could set a tag of the self.info view (or check with the indexpath you're keeping in memory), then check when you dequeue the cell if the info view is there, and remove it. The cleaner solution would be to implement the view removal by overriding the prepareForReuse method of your custom UITableViewCell
Precision
The first thing you need to do is set a tag for your self.info view after initializing it:
[self.info setTag:2222];
If you want to keep it as simple as possible, you could check and remove the self.info view directly in your cellForRowAtIndexPath method :
CategorieCell *customCell = [tableView dequeueReusableCellWithIdentifier:#"cellID" forIndexPath:indexPath];
customCell.title.text = [self.sortedDictionary objectAtIndex:indexPath.row];
if [customCell.infoView viewWithTag: 2222] != nil {
[self.info removeFromSuperview]
}
return customCell;
I am not a percent sure this code compiles, I cannot test it on my side for now. Hope it works !
I have a simple tableView in which i change the cell whenever i click it in the function like this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self shuftleCellExpansion:indexPath.row];
[tableView beginUpdates];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
}
Second Functions:
-(BOOL) shuftleCellExpansion:(int) indexP
{
if([opendedCells containsIndex:indexP])
{
[opendedCells removeIndex:indexP];
return YES;
}
else
{
[opendedCells addIndex:indexP];
return YES;
}
}
Cell for index Function:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self isCellInExpandedList:indexPath.row])
{
NSLog(#"Cell is in Expanded State %hhd for Index Path %ld",[self isCellInExpandedList:indexPath.row], (long)indexPath.row);
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"poCell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"poCell"];
cell.backgroundColor = [UIColor blueColor];
}
[[cell textLabel] setText:[searchResults objectAtIndex:indexPath.row]];
[cell imageView].image = [UIImage imageNamed:#"someicon.png"];
return cell;
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"poCell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"poCell"];
cell.backgroundColor = [UIColor redColor];
}
[[cell textLabel] setText:[searchResults objectAtIndex:indexPath.row]];
return cell;
}
No the issue is that when ever i change a specific cell and then scroll it the cell at after the specific cells (i.e. after total visible cells) i see the same changed cell .
What is the efficient way to get Rid of this?
Every cell which go off the screen goes to reuse pool (mostly all data are erase) and if you scroll back the cell is populated in cellForRowAtIndexPath: method again.
You need to change the data source if you want to keep the changes.
In your didSelectRowAtIndexPath: you need to also make the changes in the array (I assume you use array to read the data from in cellForRowAtIndexPath:) you use in cellForRowAtIndexPath: to populate cell.
Hope this help.
// EXTENDED
To make it work you need to amend shuftleCellExpansion: method. In opendedCells you swap the indexes, I believe it reflect the changes in table view. In the same method you have to reflect the changes for searchResults array as well (swap the object as you did for opendedCells).
I have an iPad app which uses a UISplitViewController (with a UITableView on the left and a detail view on the right). My table view highlights the selected cell in blue when you tap on it.
When I call the following method, the cell is selected but not highlighted in blue:
[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
I have spent literally days fiddling about with various delegate methods and hacks trying to get the cell to highlight programatically just as if it had been tapped. I can't do it.
I've managed to almost get there with this:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (shouldHighlightCell)
{
NSIndexPath *indexPathForCellToHighlight = [NSIndexPath indexPathForRow:0 inSection:0];
if ([indexPath isEqual:indexPathForCellToHighlight])
{
cell.selected = YES;
shouldHighlightCell = NO;
}
}
}
It works as long as I also have this (otherwise it remains selected even when another cell is tapped):
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:0];
if ([[self.tableView cellForRowAtIndexPath:ip] isSelected])
{
[[self.tableView cellForRowAtIndexPath:ip] setSelected:NO];
}
NSIndexPath *iToTheP = indexPath;
return iToTheP;
}
I know this is a weird and convoluted workaround. I wouldn't mind, but it doesn't even work fully. The selected cell loses its highlight if it is scrolled off screen, whereas a cell that has been tapped remains highlighted when scrolled off screen.
I'm absolutely baffled by this. I'm sure this workaround shouldn't even be necessary, that there is a much simpler solution.
Please be sure the cell's selectionStyle is UITableViewCellSelectionStyleBlue and the tableView's allowsSelection is set to YES.
The method selectRowAtIndexPath:animated:scrollPosition: works fine for me. It does highlight the selected cell.
I went through and tried all these and other solutions and no joy. In my case the problem (which drove me nuts for 2 hrs) was the following - shortly after I was calling selectRowAtIndexPath, I was calling reloadData on the tableview. That reload was wiping all the highlighting! Beware of this pitfall! With the unnecessary reloading of data call gone, the highlighting happenned as expected.
I also tried many approaches to get the initial selection to display on my single-selection UITableView. What finally worked for me was to defer the selection of the initial row until the table was set up by calling it in my UITableViewController's viewDidAppear:
override func viewDidAppear(animated: Bool)
{
tableView.selectRowAtIndexPath(indexPathToSelectInitially, animated: false, scrollPosition: .None)
}
I found this and it works for me (aka calling the delegate method didSelectRowAtIndexPath)
NSIndexPath *defaultIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self tableView:[self tableView] didSelectRowAtIndexPath:defaultIndexPath];
PS. I'm using UITableViewController.
I found this to be completely unfixable using all known possibilities. In the end I fixed it by ditching a lot of my code and switching to NSFetchedResultsController instead. NSFetchedResultsController was introduced shortly after I originally wrote this app, and it greatly simplifies the process of using Core Data with UITableViews.
https://developer.apple.com/library/IOs/documentation/CoreData/Reference/NSFetchedResultsController_Class/index.html
It gets the backgroundview with cell border looking like seperator.Do not change the default tableview settings in Interface builder.Make sure UITableViewCellSelectionStyleNone is NOT set to selectionstyle. I am pasting the working code. :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *kCellIdentifier = #"PlayListCell";
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier];
}
MPMediaPlaylist *playList = [playlistCollection objectAtIndex:indexPath.row];
cell.textLabel.text = playList.name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%d Songs",[playList.items count]];
MPMediaItemCollection *playListMediaCollection = [playlistCollection objectAtIndex:indexPath.row ];
cell.imageView.image =[UIImage imageWithCGImage:[self getImageForCollection:playListMediaCollection.items]];
// the main code which make it highlight
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:170.0f/255.0 green:170.0f/255.0 blue:170.0f/255.0 alpha:1.0f];
[bgColorView.layer setBorderColor:[UIColor blackColor].CGColor];
[bgColorView.layer setBorderWidth:1.0f];
[cell setSelectedBackgroundView:bgColorView];
return cell;
}
This may be a long question in order I'll be able to explain all the problem I've encountered.
So, I want to implement such UI functionality:
So I have a UITableView which is implemented in one file and it's cells which is implemented in other file TableViewCell.m
And I need after clicking on button read more to expand UILabel with text mesage as on the second screen and after clicking on close message button to restore UILabel and consequently resize TableView cell (this is one button i only change images of it). So in order to resize UILabel I use [UILabel sizeToFit] and change label.numberOfLines from 3 to 0 (iOS 6 feature as far as I know).And here code of creating cells:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
CPNTalkCell *cell = (CPNTalkCell *)[tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
NSString *modelId = [[models objectAtIndex:indexPath.row] valueForKey:#"modelId"];
NSDictionary *model = [[models objectAtIndex:indexPath.row] valueForKey:#"model"];
return [self setupCell:cell forModel:model withId:modelId];
}
In setupCell method I do additional adjustments and in CPNTalkCell the cell is described vi IB.
And here the code of button ReadMore event handler where I try to resize cell and label:
-(void)ResizeLabel:(id)sender
{
UIView* sender_button = (UIView*)sender;
UIButton* _resizingSenderButton = (UIButton*)sender;
CGRect _button_before = _resizingSenderButton.frame;
NSIndexPath* indexPath = [listView indexPathForCell:(UITableViewCell*)[[ sender_button superview]superview ]]; //In such an ugly way may be i
//access NSIndexpath of the current cell from
// which button was clicked
CPNTalkCell *cell = (CPNTalkCell*)[listView cellForRowAtIndexPath:indexPath];
if (cell.messageLabel.numberOfLines==3) {
[self.listView beginUpdates];
cell.messageLabel.numberOfLines=0;
[cell.messageLabel sizeToFit];
_button_before.origin.y = cell.messageLabel.frame.origin.y+ cell.messageLabel.frame.size.height+7;
_resizingSenderButton.frame=_button_before;
[_resizingSenderButton setBackgroundImage:[UIImage imageNamed:#"readmore2.png" ] forState:UIControlStateNormal];
[cell sizeToFit];
// [self.listView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.listView reloadData];
[self.listView endUpdates];
}
else
{
cell.messageLabel.numberOfLines = 3;
[self.listView beginUpdates];
[cell.messageLabel sizeToFit];
CGRect _button_after = _resizingSenderButton.frame;
_button_after.origin.y = cell.messageLabel.frame.origin.y+ cell.messageLabel.frame.size.height+7;
_resizingSenderButton.frame=_button_after;
[_resizingSenderButton setBackgroundImage:[UIImage imageNamed:#"readmore1.png" ] forState:UIControlStateNormal];
[cell sizeToFit];
[self.listView reloadData];
//[self.listView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.listView endUpdates];
}
}
So this code work and after clicking cells resize to fit the text and it's length but works strange - sometimes buttons disappear or appear on the text after scrolling the list buttons also may disappear or even text.I use reloadData when I change cell - i know it's not optimal, but as you see I've commented code of reloading of one cell because it works even more strange or not from the first clicking.
I also overload heightForRowatIndexPath:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *modelId = [[models objectAtIndex:indexPath.row] valueForKey:#"modelId"];
NSDictionary *model = [[models objectAtIndex:indexPath.row] valueForKey:#"model"];
CPNTalkCell *cell = [_cells objectForKey:modelId];
if (cell == nil) {
cell = [self setupCell:nil forModel:model withId:modelId];
}
return cell.rowHeight;
}
But in it i describe initial cell parameters before clicking on a button via calling of rowHeight described in TalkCell file!
I know it's a long question and I sometimes explain not all clear but I think iOS experts will be able to understand my problem and propose solution of this problem. I really need a help because I try to solve this problem not for a one day.Great thanks in advance!
You need to overload heightForRowAtIndexPath to return the appropriate value based on the expanded cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *mode
lId = [[models objectAtIndex:indexPath.row] valueForKey:#"modelId"];
NSDictionary *model = [[models objectAtIndex:indexPath.row] valueForKey:#"model"];
CPNTalkCell *cell = [_cells objectForKey:modelId];
if (cell == nil) {
cell = [self setupCell:nil forModel:model withId:modelId];
}
if ( indexPath == expandedIndexPath )//save the expanded cell's index path somewhere
{
return expandedCellHeight;
}
return cell.rowHeight;
}