I am trying to select a row when the table view is loaded. I've found other thread regarding this issue but they didn't solve my problem so I am asking again.
My tableview contains 5 row. And I am doing this:
if ([[dataSource objectAtIndex:indexPath.row] isEqualToString:self.status]) {
[self tableView:[self tableView] didSelectRowAtIndexPath:indexPath];
}
I've also tried cell.selected = YES; and cell.highlighted = YES;.
I am using the following code for custion selection view:
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:180/255.0
green:138/255.0
blue:171/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
Please help me selecting a row programmatically. The row is selected when I tap on the row, but can not select programmatically.
Try with following code
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
Here you need to set indexPath for row that you want to be selected.
You can get this by calling UITableView delegate method which is
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {}
inside this method you need to check every selected time that same cell are you not tapped.
if ([[myArray objectAtIndex:indexPath.row] isEqualToString:self.same])
{
[myTable selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
}
Try calling selectRowAtIndexPath on the table view object:
if ([[dataSource objectAtIndex:indexPath.row] isEqualToString:self.status])
{
[self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
}
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 UITableView that gets data from the internet when a cell is clicked it displays the UIActivity Indicator and then pushes to a Detail View controller. When I click back the UITableView cell that I clicked on has a grey background and the cell content is no longer there.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableCell";
TabelCell*cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
_activityIndicatorCell = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
// Get center of cell (vertically)
int center = [cell frame].size.height / 2;
int width = [cell frame].size.width / 1.1;
// Locate spinner in the center of the cell at end of text
[ _activityIndicatorCell setFrame:CGRectMake(width ,center - 9, 16, 16)];
[_activityIndicatorCell setHidden:YES];
[[cell contentView] addSubview:_activityIndicatorCell];
[ _activityIndicatorCell startAnimating];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
I then added this code to remove the UIActivityIndicator but its still has a grey box around the cell I clicked on and my UILabel content is no longer there.
- (void)viewWillAppear:(BOOL)animated {
[ _activityIndicatorCell stopAnimating];
[ _activityIndicatorCell hidesWhenStopped];
[self retrieveData];
}
I also reload the tableview in the retrieveData method.
Any ideas why this isn't working ?
If I add the cell data in from "numberOfRowsInSection" method it works but is this correct?
Also the cell remains grey and does not deselect even though I run:
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
adding this in to the did select method resolved the issue:
[cell setSelected:NO animated:YES];
[Edited Post]
For practicing, I developing a contact app without any backend. I followed only one NSMutableArray for maintaining contacts which is displayed in a UITableView.
Objective;
Like to search a contact (Ex: Dad), user given a name in a textfield and touch up a button
In the button action, check if Dad contain in the Mutable array which one i followed.
If present, then it definitely present in the tableView as a row. So i want to put selectionStyle for that row.
If search text changes means (Ex: Mom), then revert previous selectionStyle and apply to the row(Mom).
If not present, label notify "Not Present" as text. (Done!).
IBAction:
-(IBAction)actionSearchNameInTable:(id)sender{
if([myContactsArray containsObject:txtForContactName.text]){
myTable.tag=5;
NSInteger tempIndex=[myContactsArray indexOfObject:txtForContactName.text];
NSIndexPath *tempIndexPath=[NSIndexPath indexPathForRow:tempIndex inSection:0];
[self tableView:myTable didSelectRowAtIndexPath:tempIndexPath]; //broke here
NSLog(#"Call Passed!");
}
}
didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(myTable.tag==5){
NSLog(#"called done!");
//Here i like to select that row and apply selectionStyle or favorite background color for that cell, idea?.
myTable.tag=0;
}
These are all just other part of my application. I sured that, Delegate and Datasource are connected properly.
You are calling didDeselectRowAtIndexPath and not didSelectRowAtIndexPath.
And I think you have not implemented didDeselectRowAtIndexPath in your class so thats the reason of crash.
and for your another question:
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(cell.tag==100)
{
cell.contentView.backgroundColor=[UIColor grayColor];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tblviw cellForRowAtIndexPath:indexPath];
cell.tag=100;
cell.contentView.backgroundColor=[UIColor grayColor];
}
Change this:
-(IBAction)actionSearchNameInTable:(id)sender{
if([myContactsArray containsObject:txtForContactName.text]){
myTable.tag=5;
NSInteger tempIndex=[myContactsArray indexOfObject:txtForContactName.text];
NSLog(#"TEmp index:%i",tempIndex);
NSIndexPath *tempIndexPath=[NSIndexPath indexPathForRow:tempIndex inSection:0];
NSLog(#"Temp IP:%#",tempIndexPath);
[self tableView:myTable didSelectRowAtIndexPath]; //broke here
NSLog(#"Call Passed!");
}
}
And for custom selection background do this in your cellForRowAtIndexPath.
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:180/255.0
green:138/255.0
blue:171/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
Hope this helps.. :)
EDIT:
didSelectRowAtIndexPath is a delegate. It only get called when user interaction happens. I face a same problem some days ago. I did it in cellForRowAtIndexPath. For selecting a row do this:
if ([[myContactsArray objectAtIndex:indexPath.row] isEqualToString:txtForContactName.text]) {
[self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
}
Please try to see my edited answer...
-(IBAction)actionSearchNameInTable:(id)sender{
if([myContactsArray containsObject:txtForContactName.text]){
myTable.tag=5;
NSInteger tempIndex=[myContactsArray indexOfObject:txtForContactName.text];
NSLog(#"TEmp index:%i",tempIndex);
NSIndexPath *tempIndexPath=[NSIndexPath indexPathForRow:tempIndex inSection:0];
NSLog(#"Temp IP:%#",tempIndexPath);
[self tableView:myTable didSelectRowAtIndexPath:tempIndexPath]; //Change here......
NSLog(#"Call Passed!");
}
}
Action for searching that if given text is present or not:
-(IBAction)actionSearchNameInTable:(id)sender{
[txtForContactName resignFirstResponder];
if([myContactsArray containsObject:txtForContactName.text]){
myTable.tag=5;
[myTable reloadData];
}
}
In cellForRowAtIndexPath:
//Better delegate to apply selection style
//Code after dequeue...
myTableCell.textLabel.text=[myContactsArray objectAtIndex:indexPath.row];
myTableCell.imageView.image=[myContactsPhotosArray objectAtIndex:0];
{
myTableCell.textLabel.text=[myContactsArray objectAtIndex:indexPath.row];
myTableCell.imageView.image=[myContactsPhotosArray objectAtIndex:0];
if(myTable.tag==5){
NSLog(#"Ready to apply selectionStyle");
if ([[myContactsArray objectAtIndex:indexPath.row] isEqualToString:txtForContactName.text]) {
[myTable selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
myTable.tag=0;
}
}
return myTableCell;
}
I don't know why this doesn't work. indexOfIcon is correct, section is correct (checked with NSLog) If I select one everything is correct. But this line doesn't do a thing...why? If selected it should have a blue border. This works great while doing it "manually" but not with code..
- (void)viewWillAppear:(BOOL)animated
{
NSUInteger indexOfIcon;
if(self.mainCategory.icon){
indexOfIcon = [self.icons indexOfObject: self.mainCategory.icon];
} else {
indexOfIcon = 0;
}
[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:indexOfIcon inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionBottom];
}
add
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
cell.selected = YES;
and the cell will be selected.
The command [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:indexOfIcon inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionBottom]; tells the collectionView, that the cell is in selected state, but don't set the state of the cell.
After years selection seems to work fine (even in viewDidLoad:)
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
[_collection selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionLeft];
successfully triggers cell's -setSelected:
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;
}