UITableView on scroll doesn't call didSelectRowAtIndexPath - iphone

I have a UITableView with one section. If I click on a cell, the didSelectRowAtIndexPath is triggered as expected. but if the tableview has more rows than that can be shown in a single screen, and if I vertically scroll the tableview and click on a row, the didSelectRowAtIndexPath is not called. It is only triggered if i click on the same row one more time. Is this how the tableviews are supposed to function when you scroll? If not, is there something that I'm missing?
thanks for any help.

Thanks Tim for your input. Adding the if condition did not help though. scrolling was disabled in nib file, enabling it fixed the issue. Thanks again!!

The problem is that your cellForRowAtIndexPath is using dequeue wrong.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SingleCellIdentifier = #"selectioncell";
UITableViewCell *selectionCell = [tableView dequeueReusableCellWithIdentifier:SingleCellIdentifier];
if(selectionCell == nil)
selectionCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SingleCellIdentifier] autorelease];
[selectionCell setSelectionStyle:UITableViewCellSelectionStyleBlue];
[selectionCell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
[[selectionCell textLabel] setText:[[possibleAnswers objectAtIndex:indexPath.row] answerText]];
}
The idea is that dequeueReusableCellWithIdentifier:
gives you a usable cell, but if none is available, it returns nil; if it's nil, you should allocate it yourself. Your code was fetching the dequeued cell, but then ignoring it and simply allocing regardless of dequeue status. Try this and see if it solves your issue.

Related

Where to use scrollToRowAtIndexPath in iphone?

I am using [self.messageList scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO]; in cellForRowAtIndexPath and it is working fine, when a row is added in table array then it auto scroll upside but the problem is that when I try to see the top rows then it automatically come again last rows. And I am not able to see my all rows. Please let me know where I use this or any other approach to do this.
cellForRowAtIndexPath method is not called for all cell that you have. It is only called for visible cell in your TableView. When You Scroll UITableView then it ask to UITableView that you want to use reusable cell or add to new one. generally we use reusable cell so, it is use 1st no of cell and add at end of cell . it is not create another new cell at the end. so, when you scroll your UITableView it not scroll to end of cell it indexPath is similar to indexPath of first no of cell. so you can not scroll your UITableView at to Down.
use following code may be helpful for you.... :)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"S%1dR%1d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
[self.tblView scrollToRowAtIndexPath:indexPath atScrollPosition: UITableViewScrollPositionTop animated: YES];
// your code
}
// your code
return cell;
}
If you write this code in your cell for row at index path, then it will get called every time you try to scroll manually coz this message is called to draw your cell and you will b directed to the row you specified. Try checking your indexpath in a IF--Else block and scroll only when a certain action happens.
cellForRowAtIndexPath is a method for creating a cell to view .When you scroll this method is called when a cell is viewed.So each time the method called the [self.messageList scrollToRowAtIndexPath:indexPath method(which is called inside cellForRow) is also called and the table scrolls down to that row!!!

Modifying static cells outside cellForRowAtIndexPath without creating new cells

So I get that its typically frowned upon to modify a cell outside of the cellForRowAtIndexPath but here is what I have:
I have a static table that is used as an index of questions (1-33). Each row has a question on it and a detail disclosure indicator. All of this is manually entered in on the stoyboard.
I have a file that lists each question and some properties such as if the question has been answered.
When this screen loads (viewDidAppear) I want to check if each of these questions have been loaded and if so switch the detail indicator to a checkmark.
Now this works, for the first 5 cells. If I go to a question and come back, then even more cells are checked (even if the questions have not been answered). Is this undefined behavior because I am accessing it outside of cellForRowAtIndexPath?
Here is the code I'm using to access and change the cell:
-(void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (question1Answered)
{
UITableViewCell *cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:3]];
[cell1 setAccessoryType:UITableViewCellAccessoryCheckmark];
}
}
Again, it does work for the first 5 elements, then the rest will not change no matter what I do. Then if I go to a question and return it shows more with it selected. Strange behavior...
EDIT: I just noticed that the above code works but it only updates the cells that are currently on the screen. So if I scroll down, leave and come back all the visible cells will have the check mark. Is there a way to force a refresh of all the cells, even if they aren't visible?
Thanks for any and all help...
-David
This is similar to another question I answered few days ago. See stackoverflow.com/a/11770387/1479411
Use delegate method. Put any code that modifies the cell content and [self.tableView reloadData] in the delegate method after returning from the other view controller.
You should not update cell from viewDidAppear.
Instead you should reload data from viewDidApeear.
-(void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (question1Answered)
{
//This will call your tableview's delegate for visible cells
[self.tableView reloadData];
}
}
And inside cellForRowAtIndexPath, you should take a decision to assign accessory type.
U should first update your model then update your UI according to the model state.
For example if your model is an array of Question object, and each question has some hasBeenAnswered boolean.
Then the only thing u should do in viewDidAppear is to call [self.tableView reloadData], this will update your table view because cellForRowAtIndexPath will be called and set the cells according to your model state.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// configure the cell according to your model state
Question *question = [self.questions objectAtIndex:indexPath.row];
// check if this question has been answered
if (question.hasBeenAnswered) {
// if yes - set a checkmark
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else {
// if not - set to none (or whatever u want)
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
return cell;
}

How to select a UITableView row that is not yet shown?

I'm not sure I'm phrasing my question correctly, so here's the details.
I'm using a UITableView to display the list of available fonts. When the list is dsiplayed,
only about 12 rows show at a time, so if the previously selected font is not yet show, I can't select it when first showing the view.
What I'd like is to have the cell selected and shown in the center of the list when the view appears. But since the UITableView only loads data as needed, this is the best I can get:
EDITED
I've tried this but it doesn't work (the cell is only briefly selected while scrolling):
-(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];
}
[cell.textLabel setText:[fontArray objectAtIndex:indexPath.row]];
[cell.textLabel setFont:[UIFont fontWithName:[fontArray objectAtIndex:indexPath.row] size:16]];
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
//select the cell/row if it matches the current font
if([cell.textLabel.text isEqualToString:currentFontName]){
cell.selected=YES;
}
NSLog(#"returning cell %#",cell.textLabel);
return cell;
}
1 - Make your comparison using - (BOOL)isEqualToString:(NSString *)aString
1a - replace your test
if([cell.textLabel.text isEqualToString:currentFontName]){
cell.selected=YES;
}
by
cell.selected = [cell.textLabel.text isEqualToString:currentFontName];
1b - if you need to display your selected font you can do that before loading your TableView:
NSIndexPath * selFntPath = [NSIndexPath indexPathForRow: [fontArray indexOfObject: currentFontName]
inSection: 0];
[tableView scrollToRowAtIndexPath: selFntPath
atScrollPosition: UITableViewScrollPositionMiddle
animated: NO];
2 - Check that you do not unselect your cell in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath delegate method.
This is a classic behavior in most sample codes.
option: you can keep the select property for user selection and toggle a specific control (ie checkmark using accessoryType property your cell) to show a system-selected row.
This is probably the right approach but you can't test NSStrings for equality by pointer comparison. You want - (BOOL)isEqualToString:(NSString *)aString instead of ==.
I found the solution in another thread - the problem is related to reusing cells. If I do not re-use cells, then everything works properly. Re-using cells also caused problems with multiple checkmarks appearing when only one item is selected. Thanks to those who contributed.
EDIT: If I should not be answering my own questions please tell me...but also tell me the proper way to resolve the question!
EDIT 2: This thread also helped
UITableViewCell going black when selected programmatically

Problem updating UITableViewCells when rotating UITableView

I have a UILabel in a custom UITableViewCell that gets resized when the device is rotated. The text in this label needs to be recalculated after the rotation because I am cutting it down to size and appending some text at the end.
E.g. the datamodel has: "This is a run-on sentence that needs to stop."
In portrait mode it becomes "This is a run-on sent... more"
In landscape mode it becomes "This is a run-on sentence that... more"
From (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
I am able to access the visible UITableViewCells and update the descriptions.
The problem seems to be that there are UITableViewCells that are cached but I can't get to. When I scroll the UITableView after a rotation, one or two cells that are below the visible area after the rotation don't have the correct text in the label. So they haven't been rendered via (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath - but they weren't returned by [tableView visibleCells] (or via looping through all views returned via [tableView subViews]).
I've tried to access the "extra" cells via this method:
for (int index=max + 1; index < max + 3 && index < [cellTypes count]; index++) {
NSIndexPath *updatedPath = [NSIndexPath indexPathForRow:index inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:updatedPath];
if (cell == nil) { continue; }
[self updateCellForRotate:cell forRow:index];
}
(where max is the biggest row returned from visibleCells) but cell is always nil.
Is there anyway to flush the cache of UITableViewCells so that they don't get re-used? Or to access them so I can update them?
Thanks!
Two things.
First. In your didRotateFromInterfaceOrientation method you can simply reload the visible rows like so:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation) fromInterfaceOrientation
{
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
NSLog(#"didRotateFromInterfaceOrientation:%d",fromInterfaceOrientation);
[tableView reloadRowsAtIndexPaths:[tableView indexPathsForVisibleRows] withRowAnimation:UITableViewRowAnimationNone];
}
Then I would recommend you add either the interfaceOrientation number or simply the table width to the dequeue cell name that way the tableView knows that cells in one rotation are different from those in another. Like so:
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath withType:(NSString *)s_type
{
UITableViewCell *cell = nil;
// add width of table to the name so that rotations will change the cell dequeue names
s_cell = [s_cell stringByAppendingString:[NSString stringWithFormat:#"%#%d",#"Width",(int)tv.bounds.size.width]];
NSLog(#"%#",s_cell);
cell = [tv dequeueReusableCellWithIdentifier:s_cell];
if( cell == nil ) {
cell = [[[UITableViewCell alloc];
initWithFrame:CGRectZero reuseIdentifier:s_cell] autorelease];
}
}
Firstly, to reload all of your table cells use [self.tableView reloadData]
Secondly, add the line of code that is responsible for the shrinking inside the (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method.
Example:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//Some identifier and recycling stuff
if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
//Make labels smaller
}
else {
//Make them bigger
}
}
Or you can just call your updateCellForRotate:forRow: method when making them. But I'm not sure how that function works, so I can't be too specific.
When you create the cell in cellForRowAtIndexPath:, add it to an array. Then, loop through the array, updating the text as necessary.
Hope this helps,
jrtc27
EDIT:
You say they are custom cells - could you not update your text in your UITableViewCell subclass?
So, I was having (what I think was) a very similar problem recently, and none of the posted answers helped me, I'm sorry to say.
My issue was that I deliberately resized and repositioned the UITableView upon rotation, and I did that programatically. The table cells in portrait took up the width of the view, and in Landscape were made somewhat higher but less wide. I then repositioned the elements of the cell depending on the orientation we'd come to.
Upon application start, the first viewing of the table was fine. Then I rotated and found that I appeared to have two instances of some elements, and these appeared to be where the cells had been visible in the first table. Rotating back then corrupted the initial orientation table with elements from the previous table.
I tried all of the applicable answers above, until I looked closer at the cellForRowAtIndexPath code:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
I understand cell re-use is a great idea and all, but I really didn't need to retain (as in preserve) any cells and wanted them all bright, spangly and new after each rotation.
EDIT: In my own app I'll have maybe 20-30 rows maximum, as I personally don't like hugely long tables. If there were going to be lots of rows returned for a particular query I'd have some filters available to the user to help them sort out which rows they wanted. If you're going to have loads of rows displayed, then dequeuing them may cause you a performance impact that you don't want.
All I did was comment out the if and the following bracket, and my table cells renewed exactly as I wanted them to:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//}
Apologies for the waffle, and the late answer to an old question.
Ben.
Waffles and cream, or syrup.
You can use this simple line on the shouldAutorotateToInterfaceOrientation method :
self.view.autoresizesSubviews = YES;
For me it works always successfully

UITableView with a single custom Cell? (iPhone)

I have run into a bit of a problem. Usually when dealing with UITableView I will build a special
method, configureCell, that builds the cells as the tableView needs them. So cellForRowAtIndexPath queries the configureCell to get a new cell if none is found in the cache.
In the part of cellForRowAtIndexPath that gets run every time a user scrolls:
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
[self configureCell:cell atIndexPath:indexPath];
}
//this part is always executed!
}
I set the label values etc. from my model. This works fine and this, I believe, is how it should be to work properly and be the least strain on the CPU. From what I can read in the TableView Guide.
My problem is now that the first Cell in my tableView is different than the others. I has a special icon and other things that separates it from the other cells.
In my configure cell I then tried asking:
if (indexPath.row == 0) {
//do special setup!
}
This is a bad idea as the tableView lazy loads the cells and therefore the first cell that is off-screen, when being scrolled on-screen, will also get indexPath.row = 0 so now I have a "special cell" for every 7 cells.
How do I get around this one?
A second problem that also originates from the above: I have a custom UIView placed in all the cells accessoryView. When the user taps an "Edit" button, all the cells accessoryViews should change to an icon indicating that we are in "Edit mode". Here, again, this only happens for the cells on screen, when scrolling "old" cells are either fetched from cache or new cells are build that doesn't know we are in edit mode.
When You tap a Cell, there is never any doubt about the indexPath.row of the cell tapped, this index you need to pair with your model array to figure out what the user tapped. But it seems different rules apply when the TableView is manipulating the cells (pulling them on-screen, off-screen, deleting, adding).
I guess, I am asking; to follow best practice and not fight the SDK, what should I do to obtain the desired functionality and at which stage in the Cell life-cycle should I apply this logic?
Hope someone can guide me in the right direction:) thank You in advance:)
I think the problem is not that the first off-screen cell is at indexPath.row = 0.
The problem is that you are using the same CellIdentifier for regular and custom cells. So when the TableView goes to dequeue a cached cell, it is sometimes grabbing your custom cell that has the icon in it.
Since you gave it the same CellIdentifier as your regular cells, it doesn't know that they are not the same.
Something like this should fix it:
static NSString *CellIdentifier;
if([indexPath row] == 0){
CellIdentifier = #"CustomCell";
} else {
CellIdentifier = #"Cell";
}
I'm not sure about your edit button problem, but it could be related.